-
-
Notifications
You must be signed in to change notification settings - Fork 121
/
queries.ts
69 lines (65 loc) · 2.22 KB
/
queries.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
64
65
66
67
68
69
import { OperationResult, createRequest, Client } from 'urql';
import { pipe, subscribe, Source } from 'wonka';
import { GqlQueryOptions, GqlMutationOptions, GqlSubscriber, GqlSubscriptionOptions } from './types';
function pipeToPromise<T>(source: Source<OperationResult<T>>) {
return new Promise<T>((resolve, reject) => {
pipe(
source,
subscribe(({ data, error }) => {
if (error) {
reject(error);
} else {
resolve(data);
}
}),
);
});
}
/**
* Executes a new GraphQL query.
* @param client The client to use as base.
* @param q The GraphQL query to run.
* @param options The options for the query.
*/
export function gqlQuery<TResult = any>(client: Client, q: string, options: GqlQueryOptions = {}) {
const { variables, cache, headers = {} } = options;
const request = createRequest(q, variables);
const response = client.executeQuery(request, { requestPolicy: cache, fetchOptions: { headers } });
return pipeToPromise<TResult>(response);
}
/**
* Executes a new GraphQL mutation.
* @param client The client to use as base.
* @param q The GraphQL mutation to run.
* @param options The options for the mutation.
*/
export function gqlMutation<TResult = any>(client: Client, q: string, options: GqlMutationOptions = {}) {
const { variables, headers = {} } = options;
const request = createRequest(q, variables);
const response = client.executeMutation(request, { fetchOptions: { headers } });
return pipeToPromise<TResult>(response);
}
/**
* Establishes a new GraphQL subscription.
* @param client The client to use as base.
* @param q The GraphQL subscription to establish.
* @param subscriber The callback when new data has arrived.
* @param options The options for the query.
*/
export function gqlSubscription<TResult = any>(
client: Client,
q: string,
subscriber: GqlSubscriber<TResult>,
options: GqlSubscriptionOptions = {},
) {
const { variables, headers = {} } = options;
const request = createRequest(q, variables);
const response = client.executeSubscription(request, { fetchOptions: { headers } });
const [teardown] = pipe(
response,
subscribe(({ data, error }) => {
subscriber(data, error);
}),
);
return teardown;
}