fix: fetch preview content
This commit is contained in:
@@ -7,26 +7,35 @@ import type { Data } from "@/types/request";
|
||||
import type { DocumentNode } from "graphql";
|
||||
import ContentstackLivePreview from "@contentstack/live-preview-utils";
|
||||
|
||||
export async function request<T>(
|
||||
export async function previewRequest<T>(
|
||||
query: string | DocumentNode,
|
||||
variables?: {}
|
||||
): Promise<Data<T>> {
|
||||
try {
|
||||
const hash = ContentstackLivePreview.hash;
|
||||
|
||||
const response = await graphqlRequest<T>({
|
||||
document: query,
|
||||
requestHeaders: {
|
||||
access_token: env.CMS_ACCESS_TOKEN,
|
||||
"Content-Type": "application/json",
|
||||
preview_token: env.CMS_PREVIEW_TOKEN,
|
||||
live_preview: hash,
|
||||
},
|
||||
url: env.CMS_PREVIEW_URL,
|
||||
variables,
|
||||
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.toString(), {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
variables,
|
||||
}),
|
||||
});
|
||||
|
||||
return { data: response };
|
||||
const { data } = await response.json();
|
||||
|
||||
return data as Data<T>;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new Error("Something went wrong");
|
||||
|
||||
Reference in New Issue
Block a user