fix: add sdk as script

This commit is contained in:
Christel Westerberg
2024-02-07 15:10:02 +01:00
parent 70f7e95036
commit e48a9535ef
7 changed files with 62 additions and 38 deletions

View File

@@ -10,34 +10,38 @@ import ContentstackLivePreview from "@contentstack/live-preview-utils";
export async function previewRequest<T>(
query: string | DocumentNode,
variables?: {}
): Promise<Data<T>> {
try {
const hash = ContentstackLivePreview.hash;
): Promise<Data<T> | null> {
const hash = ContentstackLivePreview.hash;
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,
}),
});
const { data } = await response.json();
return data as Data<T>;
} catch (error) {
console.error(error);
throw new Error("Something went wrong");
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>;
}