link-stack/apps/link/app/_lib/zammad.ts

70 lines
1.6 KiB
TypeScript
Raw Normal View History

import { getServerSession } from "app/_lib/authentication";
import { cookies } from "next/headers";
const getHeaders = async () => {
2024-11-25 09:31:25 +01:00
const allCookies = (await cookies()).getAll();
const session = await getServerSession();
const headers = {
"Content-Type": "application/json",
Accept: "application/json",
2024-08-14 13:03:50 +02:00
"X-Browser-Fingerprint": `${session.expires}`,
2024-10-09 12:21:06 +02:00
// @ts-ignore
"X-CSRF-Token": session.user.zammadCsrfToken,
Cookie: allCookies
.map((cookie: any) => `${cookie.name}=${cookie.value}`)
.join("; "),
};
return headers;
};
interface ExecuteGraphQLOptions {
query: string;
variables?: Record<string, any>;
}
export const executeGraphQL = async ({
query,
variables,
}: ExecuteGraphQLOptions): Promise<any> => {
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<any> => {
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();
};