import { getServerSession } from "app/_lib/authentication"; import { redirect } from "next/navigation"; import { cookies } from "next/headers"; const getHeaders = async () => { const allCookies = cookies().getAll(); const session = await getServerSession(); const headers = { "Content-Type": "application/json", Accept: "application/json", // @ts-ignore "X-CSRF-Token": session.user.zammadCsrfToken, "X-Browser-Fingerprint": `${session.expires}`, Cookie: allCookies .map((cookie: any) => `${cookie.name}=${cookie.value}`) .join("; "), }; return headers; }; interface ExecuteGraphQLOptions { query: string; variables?: Record; } export const executeGraphQL = async ({ query, variables, }: ExecuteGraphQLOptions): Promise => { const headers = await getHeaders(); const endpoint = `${process.env.ZAMMAD_URL}/graphql`; const body = JSON.stringify({ query, ...(variables && { variables }) }); const result = await fetch(endpoint, { headers, body, method: "POST", next: { revalidate: 0 }, }); const { data, errors } = await result.json(); if (result.status !== 200) { throw new Error(`Error: ${result.status}`); } else if (errors) { throw new Error(`Error: ${JSON.stringify(errors)}`); } return data; }; interface ExecuteRESTOptions { path: string; } export const executeREST = async ({ path, }: ExecuteRESTOptions): Promise => { const headers = await getHeaders(); const result = await fetch(`${process.env.ZAMMAD_URL}${path}`, { method: "GET", headers, }); if (result.status !== 200) { throw new Error(`Error: ${result.status}`); } return await result.json(); };