|
|
@@ -20,7 +20,7 @@ import {
|
|
|
FORGET_PASSWORD,
|
|
|
} from "@/graphql/customer/mutations";
|
|
|
import { DocumentNode } from "graphql";
|
|
|
-import { GRAPHQL_URL } from "@/utils/constants";
|
|
|
+import { GRAPHQL_URL, REST_API_URL } from "@/utils/constants";
|
|
|
import {
|
|
|
GET_FOOTER,
|
|
|
GET_THEME_CUSTOMIZATION,
|
|
|
@@ -46,6 +46,91 @@ interface PageByUrlKeyResponse {
|
|
|
pageByUrlKeypages?: PageData[];
|
|
|
}
|
|
|
|
|
|
+// rest api fetch
|
|
|
+export async function restApiFetch<T>({
|
|
|
+ api,
|
|
|
+ cache = "force-cache",
|
|
|
+ headers,
|
|
|
+ tags,
|
|
|
+ variables,
|
|
|
+ isCookies = true,
|
|
|
+ guestToken,
|
|
|
+ revalidate = 60,
|
|
|
+}: {
|
|
|
+ api: string;
|
|
|
+ cache?: RequestCache;
|
|
|
+ headers?: HeadersInit | Record<string, string>;
|
|
|
+ tags?: string[];
|
|
|
+ variables?: ExtractVariables<T>;
|
|
|
+ isCookies?: boolean;
|
|
|
+ guestToken?: string;
|
|
|
+ revalidate?: number;
|
|
|
+}): Promise<{ status: number; body: T } | never> {
|
|
|
+ try {
|
|
|
+ let apiUrl = api.startsWith("http") ? api : `${REST_API_URL}${api}`;
|
|
|
+ let bagistoCartId = "";
|
|
|
+ let accessToken: string | undefined = undefined;
|
|
|
+
|
|
|
+ if (isCookies) {
|
|
|
+ const cookieStore = await cookies();
|
|
|
+ bagistoCartId = cookieStore.get(BAGISTO_SESSION)?.value ?? "";
|
|
|
+ const sessions = (await getServerSession(
|
|
|
+ authOptions,
|
|
|
+ )) as BagistoSession | null;
|
|
|
+ accessToken = sessions?.user?.accessToken;
|
|
|
+ }
|
|
|
+
|
|
|
+ const baseHeaders: Record<string, string> = {
|
|
|
+ "Content-Type": "application/json",
|
|
|
+ "X-STOREFRONT-KEY": STOREFRONT_KEY,
|
|
|
+ };
|
|
|
+
|
|
|
+ if (accessToken) {
|
|
|
+ baseHeaders.Authorization = `Bearer ${accessToken}`;
|
|
|
+ } else if (guestToken) {
|
|
|
+ baseHeaders.Authorization = `Bearer ${guestToken}`;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (bagistoCartId) {
|
|
|
+ baseHeaders.Cookie = `${BAGISTO_SESSION}=${bagistoCartId}`;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (isCookies && headers) {
|
|
|
+ if (headers instanceof Headers) {
|
|
|
+ headers.forEach((value, key) => (baseHeaders[key] = value));
|
|
|
+ } else {
|
|
|
+ Object.assign(baseHeaders, headers);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ let param = {};
|
|
|
+ if(variables) {
|
|
|
+ param = {...variables};
|
|
|
+ }
|
|
|
+
|
|
|
+ const result = await fetch(apiUrl, {
|
|
|
+ method: "POST",
|
|
|
+ headers: baseHeaders,
|
|
|
+ body: JSON.stringify(param),
|
|
|
+ cache,
|
|
|
+ next: {
|
|
|
+ revalidate: cache === "no-store" ? 0 : revalidate || 60,
|
|
|
+ ...(tags && { tags }),
|
|
|
+ },
|
|
|
+ });
|
|
|
+
|
|
|
+ const body = await result.json();
|
|
|
+
|
|
|
+ if (body.errors) throw body.errors[0];
|
|
|
+
|
|
|
+ return { status: result.status, body };
|
|
|
+ } catch (e) {
|
|
|
+ throw e;
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
export async function bagistoFetch<T>({
|
|
|
cache = "force-cache",
|
|
|
headers,
|