forked from api-platform/api-doc-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetchQuery.ts
More file actions
39 lines (31 loc) · 980 Bytes
/
Copy pathfetchQuery.ts
File metadata and controls
39 lines (31 loc) · 980 Bytes
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
import type { ExecutionResult } from "graphql";
const setOptions = (query: string, options: RequestInit): RequestInit => {
if (!options.method) {
options.method = "POST";
}
if (!(options.headers instanceof Headers)) {
options.headers = new Headers(options.headers);
}
if (null === options.headers.get("Content-Type")) {
options.headers.set("Content-Type", "application/json");
}
if ("GET" !== options.method && !options.body) {
options.body = JSON.stringify({ query });
}
return options;
};
export default async <TData = { [key: string]: unknown }>(
url: string,
query: string,
options: RequestInit = {}
): Promise<{
response: Response;
body: ExecutionResult<TData>;
}> => {
const response = await fetch(url, setOptions(query, options));
const body = (await response.json()) as ExecutionResult<TData>;
if (body?.errors) {
return Promise.reject({ response, body });
}
return Promise.resolve({ response, body });
};