-
Notifications
You must be signed in to change notification settings - Fork 10
/
utils.ts
63 lines (60 loc) · 1.57 KB
/
utils.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
59
60
61
62
63
import {
BaseOperations,
OperationData,
OperationVariables,
TypedDocumentNode,
getDocumentNode,
} from '@ts-gql/tag/no-transform';
import { print } from 'graphql/language/printer';
import {
GetStaticPathsContext,
GetStaticProps,
GetStaticPropsContext,
GetStaticPropsResult,
Redirect,
} from 'next';
type RequiredKeys<T> = {
[K in keyof T]: {} extends Pick<T, K> ? never : K;
} extends { [_ in keyof T]: infer U }
? {} extends U
? never
: U
: never;
type HasRequiredVariables<
TTypedDocumentNode extends TypedDocumentNode<BaseOperations>,
RequiredResult,
OptionalResult
> = RequiredKeys<OperationVariables<TTypedDocumentNode>> extends never
? OptionalResult
: RequiredResult;
export function fetchGraphQL<
TTypedDocumentNode extends TypedDocumentNode<BaseOperations>
>(
options: {
operation: TTypedDocumentNode;
} & HasRequiredVariables<
TTypedDocumentNode,
{ variables: OperationVariables<TTypedDocumentNode> },
{ variables?: OperationVariables<TTypedDocumentNode> }
>
): Promise<OperationData<TTypedDocumentNode>> {
return fetch('http://localhost:3000/api/graphql', {
method: 'POST',
body: JSON.stringify({
query: print(getDocumentNode(options.operation)),
variables: options.variables,
}),
headers: { 'Content-Type': 'application/json' },
})
.then(x => x.json())
.then(({ data, errors }) => {
if (errors) {
throw new Error(
`GraphQL errors occurred:\n${errors
.map((x: any) => x.message)
.join('\n')}`
);
}
return data;
});
}