/
createFetcher.ts
71 lines (66 loc) · 2.02 KB
/
createFetcher.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
70
71
import type { Fetcher, CreateFetcherOptions } from './types';
import {
createMultipartFetcher,
createSimpleFetcher,
isSubscriptionWithName,
getWsFetcher,
} from './lib';
/**
* build a GraphiQL fetcher that is:
* - backwards compatible
* - optionally supports graphql-ws or `
*
* @param options {CreateFetcherOptions}
* @returns {Fetcher}
*/
export function createGraphiQLFetcher(options: CreateFetcherOptions): Fetcher {
let httpFetch;
if (typeof window !== 'undefined' && window.fetch) {
httpFetch = window.fetch;
}
if (
options?.enableIncrementalDelivery === null ||
options.enableIncrementalDelivery !== false
) {
options.enableIncrementalDelivery = true;
}
if (options.fetch) {
httpFetch = options.fetch;
}
if (!httpFetch) {
throw new Error('No valid fetcher implementation available');
}
// simpler fetcher for schema requests
const simpleFetcher = createSimpleFetcher(options, httpFetch);
const httpFetcher = options.enableIncrementalDelivery
? createMultipartFetcher(options, httpFetch)
: simpleFetcher;
return (graphQLParams, fetcherOpts) => {
if (graphQLParams.operationName === 'IntrospectionQuery') {
return (options.schemaFetcher || simpleFetcher)(
graphQLParams,
fetcherOpts,
);
}
const isSubscription = fetcherOpts?.documentAST
? isSubscriptionWithName(
fetcherOpts.documentAST,
graphQLParams.operationName || undefined,
)
: false;
if (isSubscription) {
const wsFetcher = getWsFetcher(options, fetcherOpts);
if (!wsFetcher) {
throw new Error(
`Your GraphiQL createFetcher is not properly configured for websocket subscriptions yet. ${
options.subscriptionUrl
? `Provided URL ${options.subscriptionUrl} failed`
: 'Please provide subscriptionUrl, wsClient or legacyClient option first.'
}`,
);
}
return wsFetcher(graphQLParams);
}
return httpFetcher(graphQLParams, fetcherOpts);
};
}