44 lines
1.1 KiB
TypeScript
44 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>> {
|
|
try {
|
|
const hash = ContentstackLivePreview.hash;
|
|
|
|
if (!hash) {
|
|
throw new Error("No hash received");
|
|
}
|
|
|
|
if (!env.CMS_PREVIEW_URL || !env.CMS_PREVIEW_TOKEN) {
|
|
throw new Error("No preview URL or token");
|
|
}
|
|
|
|
const headers = new Headers({
|
|
access_token: env.CMS_ACCESS_TOKEN,
|
|
preview_token: env.CMS_PREVIEW_TOKEN,
|
|
live_preview: hash,
|
|
});
|
|
|
|
const response = await graphqlRequest<T>({
|
|
document: query,
|
|
requestHeaders: headers,
|
|
url: env.CMS_PREVIEW_URL,
|
|
variables,
|
|
});
|
|
|
|
return { data: response };
|
|
} catch (error) {
|
|
console.error(error);
|
|
throw new Error("Something went wrong");
|
|
}
|
|
}
|