48 lines
1.1 KiB
TypeScript
48 lines
1.1 KiB
TypeScript
import "server-only";
|
|
import { request as graphqlRequest } from "graphql-request";
|
|
|
|
import { env } from "@/env/server.mjs";
|
|
|
|
import type { Data } from "@/types/request";
|
|
import type { DocumentNode } from "graphql";
|
|
import ContentstackLivePreview from "@contentstack/live-preview-utils";
|
|
|
|
export async function previewRequest<T>(
|
|
query: string | DocumentNode,
|
|
variables?: {}
|
|
): Promise<Data<T> | null> {
|
|
const hash = ContentstackLivePreview.hash;
|
|
|
|
if (!hash) {
|
|
return null;
|
|
}
|
|
|
|
if (!env.CMS_PREVIEW_URL || !env.CMS_PREVIEW_TOKEN) {
|
|
throw new Error("No preview URL");
|
|
}
|
|
const headers = new Headers();
|
|
|
|
headers.append("access_token", env.CMS_ACCESS_TOKEN);
|
|
headers.append("Content-Type", "application/json");
|
|
headers.append("preview_token", env.CMS_PREVIEW_TOKEN);
|
|
headers.append("live_preview", hash);
|
|
|
|
const response = await fetch(env.CMS_PREVIEW_URL, {
|
|
method: "POST",
|
|
headers,
|
|
body: JSON.stringify({
|
|
query,
|
|
variables,
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
console.log(response);
|
|
throw new Error("Cound not fetch preview content");
|
|
}
|
|
|
|
const { data } = await response.json();
|
|
|
|
return data as Data<T>;
|
|
}
|