index.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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 { print, DocumentNode } from "graphql";
  23. import {
  24. GRAPHQL_URL,
  25. REST_API_URL,
  26. GUEST_CART_TOKEN,
  27. IS_GUEST,
  28. CURRENT_CURRENCY,
  29. CURRENT_LOCAL,
  30. CURRENT_CHANNEL,
  31. } from "@/utils/constants";
  32. import {
  33. GET_FOOTER,
  34. GET_THEME_CUSTOMIZATION,
  35. PAGE_BY_URL_KEY,
  36. } from "@/graphql";
  37. import { SUBSCRIBE_TO_NEWSLETTER } from "@/graphql/theme/mutations";
  38. import { cachedGraphQLRequest } from "@/utils/hooks/useCache";
  39. import { authOptions } from "@utils/auth";
  40. import { RegisterInputs } from "@components/customer/RegistrationForm";
  41. import {
  42. GetFooterResponse,
  43. ThemeCustomizationResult,
  44. ThemeCustomizationResponse,
  45. PageData,
  46. } from "@/types/theme/theme-customization";
  47. import { decodeJWT } from "@/utils/jwt-cookie";
  48. import {FetchGraphqlResult} from "@/types/graphqlFetch/type";
  49. type ExtractVariables<T> = T extends { variables: object }
  50. ? T["variables"]
  51. : never;
  52. interface PageByUrlKeyResponse {
  53. pageByUrlKeypages?: PageData[];
  54. }
  55. async function getBaseHeader() {
  56. /**
  57. * Headers:
  58. * X-LOCALE — locale code, e.g. "en", "fr", "ar"
  59. * X-CHANNEL — channel code, e.g. "default"
  60. * X-CURRENCY — currency code, e.g. "USD", "EUR", "INR"
  61. * */
  62. const cookieStore = await cookies();
  63. const xCurrency = cookieStore.get(CURRENT_CURRENCY)?.value; // 在proxy.ts中已经设置过值了
  64. const xLocal = cookieStore.get(CURRENT_LOCAL)?.value; // 在proxy.ts中已经设置过值了
  65. const xChannel = cookieStore.get(CURRENT_CHANNEL)?.value; // 在proxy.ts中已经设置过值了
  66. const baseHeaders: Record<string, string> = {
  67. "Content-Type": "application/json",
  68. "X-STOREFRONT-KEY": STOREFRONT_KEY,
  69. };
  70. if(xCurrency) {
  71. baseHeaders["X-Currency"] = xCurrency;
  72. }
  73. if(xLocal) {
  74. baseHeaders["X-Local"] = xLocal;
  75. }
  76. if(xChannel) {
  77. baseHeaders["X-Channel"] = xChannel;
  78. }
  79. return baseHeaders;
  80. }
  81. // rest api fetch
  82. export async function restApiFetch<T>({
  83. api,
  84. method,
  85. cache = "force-cache",
  86. headers,
  87. tags,
  88. variables,
  89. isCookies = true,
  90. guestToken,
  91. revalidate = 60,
  92. }: {
  93. api: string;
  94. method: "POST" | "GET";
  95. cache?: RequestCache;
  96. headers?: HeadersInit | Record<string, string>;
  97. tags?: string[];
  98. variables?: ExtractVariables<T>;
  99. isCookies?: boolean;
  100. guestToken?: string;
  101. revalidate?: number;
  102. }): Promise<{ status: number; body: T } | never> {
  103. try {
  104. const apiUrl = api.startsWith("http") ? api : `${REST_API_URL}${api}`;
  105. let bagistoCartId = "";
  106. let accessToken: string | undefined = undefined;
  107. if (isCookies) {
  108. const cookieStore = await cookies();
  109. bagistoCartId = cookieStore.get(BAGISTO_SESSION)?.value ?? "";
  110. const sessions = (await getServerSession(
  111. authOptions,
  112. )) as BagistoSession | null;
  113. accessToken = sessions?.user?.accessToken;
  114. }
  115. const headerRes = await getBaseHeader();
  116. const baseHeaders: Record<string, string> = {...headerRes};
  117. if (accessToken) {
  118. baseHeaders.Authorization = `Bearer ${accessToken}`;
  119. } else if (guestToken) {
  120. baseHeaders.Authorization = `Bearer ${guestToken}`;
  121. }
  122. if (bagistoCartId) {
  123. baseHeaders.Cookie = `${BAGISTO_SESSION}=${bagistoCartId}`;
  124. }
  125. if (isCookies && headers) {
  126. if (headers instanceof Headers) {
  127. headers.forEach((value, key) => (baseHeaders[key] = value));
  128. } else {
  129. Object.assign(baseHeaders, headers);
  130. }
  131. }
  132. console.log('restApiFetch --- baseHeaders:', baseHeaders)
  133. const param: RequestInit = {
  134. method: method,
  135. headers: baseHeaders,
  136. cache,
  137. next: {
  138. revalidate: cache === "no-store" ? 0 : revalidate || 60,
  139. ...(tags && { tags }),
  140. },
  141. };
  142. if(variables) {
  143. param.body = JSON.stringify({...variables});
  144. }
  145. const result = await fetch(apiUrl, param);
  146. console.log('restApiFetch --- result:', result)
  147. const body = await result.json();
  148. if (body.errors) throw body.errors[0];
  149. return { status: result.status, body };
  150. } catch (e) {
  151. throw e;
  152. }
  153. }
  154. // graphql fetch use for server side
  155. export async function serverGraphqlFetch<
  156. TData,
  157. TVariables = Record<string, never>
  158. >({
  159. cache = "no-store",
  160. headers,
  161. query,
  162. tags,
  163. variables,
  164. revalidate = 0,
  165. operationName = ''
  166. }: {
  167. cache?: RequestCache;
  168. headers?: HeadersInit | Record<string, string>;
  169. query: string | DocumentNode;
  170. tags?: string[];
  171. variables?: TVariables;
  172. revalidate?: number;
  173. operationName?: string;
  174. }): Promise<FetchGraphqlResult<TData>> {
  175. try {
  176. const queryString = typeof query === "string" ? query : print(query);
  177. let accessToken: string | undefined = undefined;
  178. let guestToken: string | undefined = undefined;
  179. const cookieStore = await cookies();
  180. const isGuest = cookieStore.get(IS_GUEST)?.value;
  181. const gt = cookieStore.get(GUEST_CART_TOKEN)?.value;
  182. if(isGuest === 'false') {
  183. // 登录用户
  184. const sessions = (await getServerSession(
  185. authOptions,
  186. )) as BagistoSession | null;
  187. accessToken = sessions?.user?.accessToken;
  188. } else if(gt) {
  189. // 游客
  190. const jwtRes = decodeJWT<{
  191. sessionToken: string;
  192. cartId: number;
  193. isGuest: boolean;
  194. }>(gt, true);
  195. guestToken = jwtRes?.sessionToken || '';
  196. }
  197. const headerRes = await getBaseHeader();
  198. const baseHeaders: Record<string, string> = {...headerRes};
  199. if (accessToken) {
  200. baseHeaders['Authorization'] = `Bearer ${accessToken}`;
  201. } else if (guestToken) {
  202. baseHeaders['Authorization'] = `Bearer ${guestToken}`;
  203. }
  204. if (headers) {
  205. if (headers instanceof Headers) {
  206. headers.forEach((value, key) => (baseHeaders[key] = value));
  207. } else {
  208. Object.assign(baseHeaders, headers);
  209. }
  210. }
  211. console.log('serverGraphqlFetch --- baseHeaders:', baseHeaders);
  212. const result = await fetch(GRAPHQL_URL, {
  213. method: "POST",
  214. headers: baseHeaders,
  215. body: JSON.stringify({
  216. query: queryString,
  217. ...(variables && { variables }),
  218. }),
  219. cache,
  220. next: {
  221. revalidate: cache === "no-store" ? 0 : revalidate || 60,
  222. ...(tags && { tags }),
  223. },
  224. });
  225. const body = await result.json();
  226. console.log('serverGraphqlFetch --- body:',body);
  227. if (body.errors) {
  228. if(operationName === 'GetCartItem' && body.errors[0].message === 'Cart not found') {
  229. return { status: result.status, data: body.data, error: null };
  230. } else {
  231. return { status: result.status, data: body.data, error: body.errors[0] };
  232. }
  233. }
  234. return { status: result.status, data: body.data,error: null };
  235. } catch (e) {
  236. throw e;
  237. }
  238. }
  239. // graphql fetch use for route handler
  240. export async function bagistoFetch<T>({
  241. cache = "force-cache",
  242. headers,
  243. query,
  244. tags,
  245. variables,
  246. isCookies = true,
  247. guestToken,
  248. revalidate = 60,
  249. operationName = ''
  250. }: {
  251. cache?: RequestCache;
  252. headers?: HeadersInit | Record<string, string>;
  253. query: string | DocumentNode;
  254. tags?: string[];
  255. variables?: ExtractVariables<T>;
  256. isCookies?: boolean;
  257. guestToken?: string;
  258. revalidate?: number;
  259. operationName?: string;
  260. }): Promise<{ status: number; body: T } | never> {
  261. try {
  262. const queryString =
  263. typeof query === "string" ? query : print(query);
  264. let bagistoCartId = "";
  265. let accessToken: string | undefined = undefined;
  266. if (isCookies) {
  267. const cookieStore = await cookies();
  268. bagistoCartId = cookieStore.get(BAGISTO_SESSION)?.value ?? "";
  269. const sessions = (await getServerSession(
  270. authOptions,
  271. )) as BagistoSession | null;
  272. accessToken = sessions?.user?.accessToken;
  273. }
  274. const headerRes = await getBaseHeader();
  275. const baseHeaders: Record<string, string> = {...headerRes};
  276. if (accessToken) {
  277. baseHeaders.Authorization = `Bearer ${accessToken}`;
  278. } else if (guestToken) {
  279. baseHeaders.Authorization = `Bearer ${guestToken}`;
  280. }
  281. if (bagistoCartId) {
  282. baseHeaders.Cookie = `${BAGISTO_SESSION}=${bagistoCartId}`;
  283. }
  284. if (isCookies && headers) {
  285. if (headers instanceof Headers) {
  286. headers.forEach((value, key) => (baseHeaders[key] = value));
  287. } else {
  288. Object.assign(baseHeaders, headers);
  289. }
  290. }
  291. // let cc = await cookies();
  292. // console.log('bagistoFetch --- url:', GRAPHQL_URL,isCookies);
  293. // console.log('bagistoFetch --- queryString:', queryString);
  294. console.log('bagistoFetch --- baseHeaders:', baseHeaders);
  295. // console.log('bagistoFetch --- cookies:', cc.getAll());
  296. // console.log('bagistoFetch --- variables:', variables);
  297. const result = await fetch(GRAPHQL_URL, {
  298. method: "POST",
  299. headers: baseHeaders,
  300. body: JSON.stringify({
  301. query: queryString,
  302. ...(variables && { variables }),
  303. }),
  304. cache,
  305. next: {
  306. revalidate: cache === "no-store" ? 0 : revalidate || 60,
  307. ...(tags && { tags }),
  308. },
  309. });
  310. const body = await result.json();
  311. console.log('bagistoFetch --- body:',body);
  312. if (body.errors) {
  313. if(operationName === 'GetCartItem' && body.errors[0].message === 'Cart not found') {
  314. return { status: result.status, body };
  315. }
  316. throw body.errors[0]
  317. }
  318. return { status: result.status, body };
  319. } catch (e) {
  320. throw e;
  321. }
  322. }
  323. /*
  324. export async function bagistoFetchNoSession<T>({
  325. query,
  326. tags,
  327. variables,
  328. headers,
  329. cache = "force-cache",
  330. revalidate = 60,
  331. }: {
  332. query: string;
  333. tags?: string[];
  334. variables?: ExtractVariables<T>;
  335. headers?: HeadersInit | Record<string, string>;
  336. cache?: RequestCache;
  337. isCookies?: boolean;
  338. revalidate?: number;
  339. }): Promise<{ status: number; body: T } | never> {
  340. try {
  341. const result = await fetch(GRAPHQL_URL, {
  342. method: "POST",
  343. headers: {
  344. "Content-Type": "application/json",
  345. "X-STOREFRONT-KEY": STOREFRONT_KEY,
  346. "x-locale": "en",
  347. "x-currency": "USD",
  348. ...headers,
  349. },
  350. body: JSON.stringify({
  351. ...(query && { query }),
  352. ...(variables && { variables }),
  353. }),
  354. cache,
  355. next: {
  356. revalidate: cache === "no-store" ? 0 : revalidate || 60,
  357. ...(tags && { tags }),
  358. },
  359. });
  360. const body = await result.json();
  361. if (body.errors) {
  362. throw body.errors[0];
  363. }
  364. return {
  365. status: result.status,
  366. body,
  367. };
  368. } catch (e) {
  369. throw { error: e, query };
  370. }
  371. }
  372. */
  373. export const removeEdgesAndNodes = <T>(array: Array<T>) => {
  374. return array?.map((edge) => edge);
  375. };
  376. const reshapeImages = (images: Array<ImageInfo>, productTitle: string) => {
  377. const flattened = removeEdgesAndNodes(images);
  378. return flattened.map((image) => {
  379. const filename = image?.url.match(/.*\/(.*)\..*/)?.[1];
  380. return {
  381. ...image,
  382. altText: image?.altText || `${productTitle} - ${filename}`,
  383. };
  384. });
  385. };
  386. const reshapeProduct = (
  387. product: BagistoProductInfo,
  388. filterHiddenProducts: boolean = true,
  389. ) => {
  390. if (
  391. !product ||
  392. (filterHiddenProducts && product.tags?.includes(HIDDEN_PRODUCT_TAG))
  393. ) {
  394. return undefined;
  395. }
  396. const { images, variants, ...rest } = product;
  397. return {
  398. ...rest,
  399. images: reshapeImages(images, product.title),
  400. variants: removeEdgesAndNodes(variants),
  401. };
  402. };
  403. export const reshapeProducts = (products: BagistoProductInfo[]) => {
  404. const reshapedProducts = [];
  405. for (const product of products) {
  406. if (product) {
  407. const reshapedProduct = reshapeProduct(product);
  408. if (reshapedProduct) {
  409. reshapedProducts.push(reshapedProduct);
  410. }
  411. }
  412. }
  413. return reshapedProducts;
  414. };
  415. export async function createUserToLogin(
  416. input: RegisterInputs,
  417. ): Promise<BagistoUser> {
  418. try {
  419. const { passwordConfirmation, ...userInput } = input;
  420. const res = await bagistoFetch<BagistoCreateUserOperation>({
  421. query: CUSTOMER_REGISTRATION,
  422. variables: {
  423. input: {
  424. ...userInput,
  425. confirmPassword: passwordConfirmation,
  426. status: "1",
  427. isVerified: "1",
  428. isSuspended: "0",
  429. subscribedToNewsLetter: true,
  430. },
  431. },
  432. cache: "no-store",
  433. revalidate: 3600,
  434. });
  435. return res.body.data.createCustomer.customer;
  436. } catch (error: any) {
  437. throw new Error(error?.message || "Registration failed");
  438. }
  439. }
  440. export async function logoutUser() {
  441. try {
  442. const session = await getServerSession(authOptions);
  443. const token = session?.user?.accessToken;
  444. if (!token) {
  445. return {
  446. success: false,
  447. message: "User token missing",
  448. };
  449. }
  450. /**
  451. * @todo CUSTOMER_LOGOUT 接口会报错,待修复(确定是php后端接口报错)
  452. */
  453. const res = await bagistoFetch<{
  454. data: { createLogout: { logout: { success: boolean; message: string } } };
  455. variables: { input: { token: string } };
  456. }>({
  457. query: CUSTOMER_LOGOUT,
  458. isCookies: true,
  459. revalidate: 3600,
  460. });
  461. const success = res?.body?.data?.createLogout?.logout?.success ?? false;
  462. const message =
  463. res?.body?.data?.createLogout?.logout?.message ?? "Logout executed";
  464. const cookieStore = await cookies();
  465. cookieStore.delete(BAGISTO_SESSION);
  466. return {
  467. success,
  468. message,
  469. };
  470. } catch (error: unknown) {
  471. return {
  472. success: false,
  473. message: error instanceof Error ? error.message : "Something went wrong",
  474. };
  475. }
  476. }
  477. export async function recoverUserLogin(
  478. input: Record<string, unknown>,
  479. ): Promise<unknown> {
  480. try {
  481. return await bagistoFetch<{
  482. data: unknown;
  483. variables: Record<string, unknown>;
  484. }>({
  485. query: FORGET_PASSWORD,
  486. variables: {
  487. ...input,
  488. },
  489. cache: "no-store",
  490. revalidate: 3600,
  491. });
  492. } catch (error) {
  493. return error;
  494. }
  495. }
  496. export async function subscribeUser(
  497. input: Record<string, unknown>,
  498. ): Promise<unknown> {
  499. try {
  500. return await bagistoFetch<{
  501. data: unknown;
  502. variables: Record<string, unknown>;
  503. }>({
  504. query: SUBSCRIBE_TO_NEWSLETTER,
  505. variables: {
  506. ...input,
  507. },
  508. cache: "no-store",
  509. });
  510. } catch (error) {
  511. return error;
  512. }
  513. }
  514. export async function getThemeCustomization(): Promise<ThemeCustomizationResult> {
  515. try {
  516. const [{data: footerRes}, {data:servicesRes}] = await Promise.all([
  517. cachedGraphQLRequest<GetFooterResponse>("static", GET_FOOTER, {
  518. type: "footer_links",
  519. }),
  520. cachedGraphQLRequest<GetFooterResponse>("static", GET_FOOTER, {
  521. type: "services_content",
  522. }),
  523. ]);
  524. return {
  525. footer_links: footerRes,
  526. services_content: servicesRes,
  527. };
  528. } catch (err) {
  529. console.error("ThemeCustomization Error:", err);
  530. }
  531. return {
  532. footer_links: null,
  533. services_content: null,
  534. };
  535. }
  536. export async function revalidate(req: NextRequest): Promise<NextResponse> {
  537. const collectionWebhooks = [
  538. "collections/create",
  539. "collections/delete",
  540. "collections/update",
  541. ];
  542. const productWebhooks = [
  543. "products/create",
  544. "products/delete",
  545. "products/update",
  546. ];
  547. const topic = (await headers()).get("x-bagisto-topic") || "unknown";
  548. const secret = req.nextUrl.searchParams.get("secret");
  549. const isCollectionUpdate = collectionWebhooks.includes(topic);
  550. const isProductUpdate = productWebhooks.includes(topic);
  551. if (!secret || secret !== process.env.BAGISTO_REVALIDATION_SECRET) {
  552. return NextResponse.json({ status: 200 });
  553. }
  554. if (!isCollectionUpdate && !isProductUpdate) {
  555. return NextResponse.json({ status: 200, message: "No action needed" });
  556. }
  557. if (isProductUpdate) {
  558. revalidatePath("/", "layout");
  559. } else if (isCollectionUpdate) {
  560. revalidatePath("/", "layout");
  561. }
  562. return NextResponse.json({
  563. status: 200,
  564. revalidated: true,
  565. topic,
  566. now: Date.now(),
  567. });
  568. }
  569. export async function getHomePageData(): Promise<ThemeCustomizationResponse> {
  570. const res = await bagistoFetch<{
  571. data: ThemeCustomizationResponse;
  572. variables: { first: number };
  573. }>({
  574. query: GET_THEME_CUSTOMIZATION,
  575. variables: { first: 20 },
  576. tags: ["theme-customization"],
  577. revalidate: 60,
  578. });
  579. return res.body.data;
  580. }
  581. export async function getPage(input: { urlKey: string }): Promise<PageData[]> {
  582. const res = await bagistoFetch<{
  583. data: PageByUrlKeyResponse;
  584. variables: { pageByUrlKey: string };
  585. }>({
  586. query: PAGE_BY_URL_KEY,
  587. cache: "no-store",
  588. isCookies: false,
  589. variables: { pageByUrlKey: input.urlKey },
  590. });
  591. return res.body.data?.pageByUrlKeypages || [];
  592. }