/
graphql.ts
43 lines (37 loc) · 1.12 KB
/
graphql.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
import type { ExecutionResult } from 'graphql'
/**
* Identity function that returns a given template string array.
* Provides GraphQL syntax highlighting without any extra transformations.
*/
export const gql = (str: TemplateStringsArray) => {
return str.join('')
}
interface GraphQLClientOPtions {
uri: string
fetch?: typeof fetch
}
interface GraphQLOperationInput {
query: TemplateStringsArray | string
variables?: Record<string, any>
}
/**
* Create a new GraphQL client. Uses `fetch` to dispatch a
* specification-compliant GraphQL request.
*/
export function createGraphQLClient(options: GraphQLClientOPtions) {
const fetchFn = options.fetch || fetch
return async (input: GraphQLOperationInput): Promise<ExecutionResult> => {
const res = await fetchFn(options.uri, {
method: 'POST',
headers: {
accept: '*/*',
'content-type': 'application/json',
},
body: JSON.stringify(input),
})
// No need to transform the JSON into `ExecutionResult`,
// because that's the responsibility of an actual server
// or an MSW request handler.
return res.json()
}
}