/
githubmirror
/
next.js
Обзор
Документация
Войти
/
githubmirror
/
next.js
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
canary
examples/cms-wordpress/src/utils/fetchGraphQL.ts
61 строка
1 KB
Bjørn Nyborg
examples: Updating WordPress example to Next 14 (#62447)
29 авг 2024, 02:09
Не верифицирован
29 авг 2024, 02:09
1207df6
Код
Авторство
О чём код?
import { draftMode, cookies } from "next/headers"; export async function fetchGraphQL<T = any>( query: string, variables?: { [key: string]: any }, headers?: { [key: string]: string }, ): Promise<T> { const { isEnabled: preview } = draftMode(); try { let authHeader = ""; if (preview) { const auth = cookies().get("wp_jwt")?.value; if (auth) { authHeader = `Bearer ${auth}`; } } const body = JSON.stringify({ query, variables: { preview, ...variables, }, }); const response = await fetch( `${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/graphql`, { method: "POST", headers: { "Content-Type": "application/json", ...(authHeader && { Authorization: authHeader }), ...headers, }, body, cache: preview ? "no-cache" : "default", next: { tags: ["wordpress"], }, }, ); if (!response.ok) { console.error("Response Status:", response); throw new Error(response.statusText); } const data = await response.json(); if (data.errors) { console.error("GraphQL Errors:", data.errors); throw new Error("Error executing GraphQL query"); } return data.data; } catch (error) { console.error(error); throw error; } }