-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.ts
58 lines (47 loc) · 1.27 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { GetStaticPropsContext } from 'next';
import { ParsedUrlQuery } from 'querystring';
interface PreviewData {
previewToken?: string;
}
interface Variables {
[key: string]: any;
}
export const client = (context?: GetStaticPropsContext<ParsedUrlQuery>) => {
let endpoint = process.env.NEXT_PUBLIC_GRAPH_URL ?? process.env.GRAPH_URL;
const previewData = (context?.previewData as PreviewData) ?? null;
if (previewData?.previewToken) {
endpoint += `?token=${previewData?.previewToken}`;
}
const request = async <T = any>(query: string, variables: Variables = {}): Promise<T> => {
const headers: HeadersInit = {
'Content-Type': 'application/json',
Accept: 'application/json',
};
if (process.env.GRAPH_TOKEN) {
headers['Authorization'] = `Bearer ${process.env.GRAPH_TOKEN}`;
}
interface Response {
data: T;
errors: {
message: string;
}[];
}
const { data, errors }: Response = await (
await fetch(endpoint, {
method: 'POST',
headers,
body: JSON.stringify({
query: String(query),
variables,
}),
})
).json();
if (errors?.length) {
throw new Error(errors[0].message);
}
return data;
};
return {
request,
};
};