index.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. import { cookies, headers } from "next/headers";
  2. import { revalidatePath } from "next/cache";
  3. import { NextRequest, NextResponse } from "next/server";
  4. import {
  5. BagistoCreateUserOperation,
  6. BagistoProductInfo,
  7. BagistoSession,
  8. BagistoUser,
  9. ImageInfo,
  10. } from "@/types/types";
  11. import {
  12. BAGISTO_SESSION,
  13. HIDDEN_PRODUCT_TAG,
  14. STOREFRONT_KEY,
  15. } from "../constants";
  16. import { getServerSession } from "next-auth";
  17. import {
  18. CUSTOMER_LOGOUT,
  19. CUSTOMER_REGISTRATION,
  20. FORGET_PASSWORD,
  21. } from "@/graphql/customer/mutations";
  22. import { DocumentNode } from "graphql";
  23. import { GRAPHQL_URL, REST_API_URL } from "@/utils/constants";
  24. import {
  25. GET_FOOTER,
  26. GET_THEME_CUSTOMIZATION,
  27. PAGE_BY_URL_KEY,
  28. } from "@/graphql";
  29. import { SUBSCRIBE_TO_NEWSLETTER } from "@/graphql/theme/mutations";
  30. import { cachedGraphQLRequest } from "@/utils/hooks/useCache";
  31. import { authOptions } from "@utils/auth";
  32. import { RegisterInputs } from "@components/customer/RegistrationForm";
  33. import {
  34. GetFooterResponse,
  35. ThemeCustomizationResult,
  36. ThemeCustomizationResponse,
  37. PageData,
  38. } from "@/types/theme/theme-customization";
  39. type ExtractVariables<T> = T extends { variables: object }
  40. ? T["variables"]
  41. : never;
  42. interface PageByUrlKeyResponse {
  43. pageByUrlKeypages?: PageData[];
  44. }
  45. // rest api fetch
  46. export async function restApiFetch<T>({
  47. api,
  48. cache = "force-cache",
  49. headers,
  50. tags,
  51. variables,
  52. isCookies = true,
  53. guestToken,
  54. revalidate = 60,
  55. }: {
  56. api: string;
  57. cache?: RequestCache;
  58. headers?: HeadersInit | Record<string, string>;
  59. tags?: string[];
  60. variables?: ExtractVariables<T>;
  61. isCookies?: boolean;
  62. guestToken?: string;
  63. revalidate?: number;
  64. }): Promise<{ status: number; body: T } | never> {
  65. try {
  66. let apiUrl = api.startsWith("http") ? api : `${REST_API_URL}${api}`;
  67. let bagistoCartId = "";
  68. let accessToken: string | undefined = undefined;
  69. if (isCookies) {
  70. const cookieStore = await cookies();
  71. bagistoCartId = cookieStore.get(BAGISTO_SESSION)?.value ?? "";
  72. const sessions = (await getServerSession(
  73. authOptions,
  74. )) as BagistoSession | null;
  75. accessToken = sessions?.user?.accessToken;
  76. }
  77. const baseHeaders: Record<string, string> = {
  78. "Content-Type": "application/json",
  79. "X-STOREFRONT-KEY": STOREFRONT_KEY,
  80. };
  81. if (accessToken) {
  82. baseHeaders.Authorization = `Bearer ${accessToken}`;
  83. } else if (guestToken) {
  84. baseHeaders.Authorization = `Bearer ${guestToken}`;
  85. }
  86. if (bagistoCartId) {
  87. baseHeaders.Cookie = `${BAGISTO_SESSION}=${bagistoCartId}`;
  88. }
  89. if (isCookies && headers) {
  90. if (headers instanceof Headers) {
  91. headers.forEach((value, key) => (baseHeaders[key] = value));
  92. } else {
  93. Object.assign(baseHeaders, headers);
  94. }
  95. }
  96. let param = {};
  97. if(variables) {
  98. param = {...variables};
  99. }
  100. const result = await fetch(apiUrl, {
  101. method: "POST",
  102. headers: baseHeaders,
  103. body: JSON.stringify(param),
  104. cache,
  105. next: {
  106. revalidate: cache === "no-store" ? 0 : revalidate || 60,
  107. ...(tags && { tags }),
  108. },
  109. });
  110. const body = await result.json();
  111. if (body.errors) throw body.errors[0];
  112. return { status: result.status, body };
  113. } catch (e) {
  114. throw e;
  115. }
  116. }
  117. export async function bagistoFetch<T>({
  118. cache = "force-cache",
  119. headers,
  120. query,
  121. tags,
  122. variables,
  123. isCookies = true,
  124. guestToken,
  125. revalidate = 60,
  126. }: {
  127. cache?: RequestCache;
  128. headers?: HeadersInit | Record<string, string>;
  129. query: string | DocumentNode;
  130. tags?: string[];
  131. variables?: ExtractVariables<T>;
  132. isCookies?: boolean;
  133. guestToken?: string;
  134. revalidate?: number;
  135. }): Promise<{ status: number; body: T } | never> {
  136. try {
  137. const queryString =
  138. typeof query === "string" ? query : (query.loc?.source?.body ?? "");
  139. let bagistoCartId = "";
  140. let accessToken: string | undefined = undefined;
  141. if (isCookies) {
  142. const cookieStore = await cookies();
  143. bagistoCartId = cookieStore.get(BAGISTO_SESSION)?.value ?? "";
  144. const sessions = (await getServerSession(
  145. authOptions,
  146. )) as BagistoSession | null;
  147. accessToken = sessions?.user?.accessToken;
  148. }
  149. const baseHeaders: Record<string, string> = {
  150. "Content-Type": "application/json",
  151. "X-STOREFRONT-KEY": STOREFRONT_KEY,
  152. };
  153. if (accessToken) {
  154. baseHeaders.Authorization = `Bearer ${accessToken}`;
  155. } else if (guestToken) {
  156. baseHeaders.Authorization = `Bearer ${guestToken}`;
  157. }
  158. if (bagistoCartId) {
  159. baseHeaders.Cookie = `${BAGISTO_SESSION}=${bagistoCartId}`;
  160. }
  161. if (isCookies && headers) {
  162. if (headers instanceof Headers) {
  163. headers.forEach((value, key) => (baseHeaders[key] = value));
  164. } else {
  165. Object.assign(baseHeaders, headers);
  166. }
  167. }
  168. const result = await fetch(GRAPHQL_URL, {
  169. method: "POST",
  170. headers: baseHeaders,
  171. body: JSON.stringify({
  172. query: queryString,
  173. ...(variables && { variables }),
  174. }),
  175. cache,
  176. next: {
  177. revalidate: cache === "no-store" ? 0 : revalidate || 60,
  178. ...(tags && { tags }),
  179. },
  180. });
  181. const body = await result.json();
  182. if (body.errors) throw body.errors[0];
  183. return { status: result.status, body };
  184. } catch (e) {
  185. throw e;
  186. }
  187. }
  188. export async function bagistoFetchNoSession<T>({
  189. query,
  190. tags,
  191. variables,
  192. headers,
  193. cache = "force-cache",
  194. revalidate = 60,
  195. }: {
  196. query: string;
  197. tags?: string[];
  198. variables?: ExtractVariables<T>;
  199. headers?: HeadersInit | Record<string, string>;
  200. cache?: RequestCache;
  201. isCookies?: boolean;
  202. revalidate?: number;
  203. }): Promise<{ status: number; body: T } | never> {
  204. try {
  205. const result = await fetch(GRAPHQL_URL, {
  206. method: "POST",
  207. headers: {
  208. "Content-Type": "application/json",
  209. "X-STOREFRONT-KEY": STOREFRONT_KEY,
  210. "x-locale": "en",
  211. "x-currency": "USD",
  212. ...headers,
  213. },
  214. body: JSON.stringify({
  215. ...(query && { query }),
  216. ...(variables && { variables }),
  217. }),
  218. cache,
  219. next: {
  220. revalidate: cache === "no-store" ? 0 : revalidate || 60,
  221. ...(tags && { tags }),
  222. },
  223. });
  224. const body = await result.json();
  225. if (body.errors) {
  226. throw body.errors[0];
  227. }
  228. return {
  229. status: result.status,
  230. body,
  231. };
  232. } catch (e) {
  233. throw { error: e, query };
  234. }
  235. }
  236. export const removeEdgesAndNodes = <T>(array: Array<T>) => {
  237. return array?.map((edge) => edge);
  238. };
  239. const reshapeImages = (images: Array<ImageInfo>, productTitle: string) => {
  240. const flattened = removeEdgesAndNodes(images);
  241. return flattened.map((image) => {
  242. const filename = image?.url.match(/.*\/(.*)\..*/)?.[1];
  243. return {
  244. ...image,
  245. altText: image?.altText || `${productTitle} - ${filename}`,
  246. };
  247. });
  248. };
  249. const reshapeProduct = (
  250. product: BagistoProductInfo,
  251. filterHiddenProducts: boolean = true,
  252. ) => {
  253. if (
  254. !product ||
  255. (filterHiddenProducts && product.tags?.includes(HIDDEN_PRODUCT_TAG))
  256. ) {
  257. return undefined;
  258. }
  259. const { images, variants, ...rest } = product;
  260. return {
  261. ...rest,
  262. images: reshapeImages(images, product.title),
  263. variants: removeEdgesAndNodes(variants),
  264. };
  265. };
  266. export const reshapeProducts = (products: BagistoProductInfo[]) => {
  267. const reshapedProducts = [];
  268. for (const product of products) {
  269. if (product) {
  270. const reshapedProduct = reshapeProduct(product);
  271. if (reshapedProduct) {
  272. reshapedProducts.push(reshapedProduct);
  273. }
  274. }
  275. }
  276. return reshapedProducts;
  277. };
  278. export async function createUserToLogin(
  279. input: RegisterInputs,
  280. ): Promise<BagistoUser> {
  281. try {
  282. const { passwordConfirmation, ...userInput } = input;
  283. const res = await bagistoFetch<BagistoCreateUserOperation>({
  284. query: CUSTOMER_REGISTRATION,
  285. variables: {
  286. input: {
  287. ...userInput,
  288. confirmPassword: passwordConfirmation,
  289. status: "1",
  290. isVerified: "1",
  291. isSuspended: "0",
  292. subscribedToNewsLetter: true,
  293. },
  294. },
  295. cache: "no-store",
  296. revalidate: 3600,
  297. });
  298. return res.body.data.createCustomer.customer;
  299. } catch (error: any) {
  300. throw new Error(error?.message || "Registration failed");
  301. }
  302. }
  303. export async function logoutUser() {
  304. try {
  305. const session = await getServerSession(authOptions);
  306. const token = session?.user?.accessToken;
  307. if (!token) {
  308. return {
  309. success: false,
  310. message: "User token missing",
  311. };
  312. }
  313. const res = await bagistoFetch<{
  314. data: { createLogout: { logout: { success: boolean; message: string } } };
  315. variables: { input: { token: string } };
  316. }>({
  317. query: CUSTOMER_LOGOUT,
  318. isCookies: true,
  319. revalidate: 3600,
  320. });
  321. const success = res?.body?.data?.createLogout?.logout?.success ?? false;
  322. const message =
  323. res?.body?.data?.createLogout?.logout?.message ?? "Logout executed";
  324. const cookieStore = await cookies();
  325. cookieStore.delete(BAGISTO_SESSION);
  326. return {
  327. success,
  328. message,
  329. };
  330. } catch (error: unknown) {
  331. return {
  332. success: false,
  333. message: error instanceof Error ? error.message : "Something went wrong",
  334. };
  335. }
  336. }
  337. export async function recoverUserLogin(
  338. input: Record<string, unknown>,
  339. ): Promise<unknown> {
  340. try {
  341. return await bagistoFetch<{
  342. data: unknown;
  343. variables: Record<string, unknown>;
  344. }>({
  345. query: FORGET_PASSWORD,
  346. variables: {
  347. ...input,
  348. },
  349. cache: "no-store",
  350. revalidate: 3600,
  351. });
  352. } catch (error) {
  353. return error;
  354. }
  355. }
  356. export async function subscribeUser(
  357. input: Record<string, unknown>,
  358. ): Promise<unknown> {
  359. try {
  360. return await bagistoFetch<{
  361. data: unknown;
  362. variables: Record<string, unknown>;
  363. }>({
  364. query: SUBSCRIBE_TO_NEWSLETTER,
  365. variables: {
  366. ...input,
  367. },
  368. cache: "no-store",
  369. });
  370. } catch (error) {
  371. return error;
  372. }
  373. }
  374. export async function getThemeCustomization(): Promise<ThemeCustomizationResult> {
  375. try {
  376. const [footerRes, servicesRes] = await Promise.all([
  377. cachedGraphQLRequest<GetFooterResponse>("static", GET_FOOTER, {
  378. type: "footer_links",
  379. }),
  380. cachedGraphQLRequest<GetFooterResponse>("static", GET_FOOTER, {
  381. type: "services_content",
  382. }),
  383. ]);
  384. return {
  385. footer_links: footerRes,
  386. services_content: servicesRes,
  387. };
  388. } catch (err) {
  389. console.error("ThemeCustomization Error:", err);
  390. }
  391. return {
  392. footer_links: null,
  393. services_content: null,
  394. };
  395. }
  396. export async function revalidate(req: NextRequest): Promise<NextResponse> {
  397. const collectionWebhooks = [
  398. "collections/create",
  399. "collections/delete",
  400. "collections/update",
  401. ];
  402. const productWebhooks = [
  403. "products/create",
  404. "products/delete",
  405. "products/update",
  406. ];
  407. const topic = (await headers()).get("x-bagisto-topic") || "unknown";
  408. const secret = req.nextUrl.searchParams.get("secret");
  409. const isCollectionUpdate = collectionWebhooks.includes(topic);
  410. const isProductUpdate = productWebhooks.includes(topic);
  411. if (!secret || secret !== process.env.BAGISTO_REVALIDATION_SECRET) {
  412. return NextResponse.json({ status: 200 });
  413. }
  414. if (!isCollectionUpdate && !isProductUpdate) {
  415. return NextResponse.json({ status: 200, message: "No action needed" });
  416. }
  417. if (isProductUpdate) {
  418. revalidatePath("/", "layout");
  419. } else if (isCollectionUpdate) {
  420. revalidatePath("/", "layout");
  421. }
  422. return NextResponse.json({
  423. status: 200,
  424. revalidated: true,
  425. topic,
  426. now: Date.now(),
  427. });
  428. }
  429. export async function getHomePageData(): Promise<ThemeCustomizationResponse> {
  430. const res = await bagistoFetch<{
  431. data: ThemeCustomizationResponse;
  432. variables: { first: number };
  433. }>({
  434. query: GET_THEME_CUSTOMIZATION,
  435. variables: { first: 20 },
  436. tags: ["theme-customization"],
  437. revalidate: 60,
  438. });
  439. return res.body.data;
  440. }
  441. export async function getPage(input: { urlKey: string }): Promise<PageData[]> {
  442. const res = await bagistoFetch<{
  443. data: PageByUrlKeyResponse;
  444. variables: { pageByUrlKey: string };
  445. }>({
  446. query: PAGE_BY_URL_KEY,
  447. cache: "no-store",
  448. isCookies: false,
  449. variables: { pageByUrlKey: input.urlKey },
  450. });
  451. return res.body.data?.pageByUrlKeypages || [];
  452. }