-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
createFetcher.ts
71 lines (64 loc) · 2.14 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';
import { createSseFetcher } from './create-sse-fetcher';
/**
* Build a GraphiQL fetcher that is:
* - backwards compatible
* - optionally supports graphql-ws or graphql-sse
*/
export function createGraphiQLFetcher(options: CreateFetcherOptions): Fetcher {
const httpFetch =
options.fetch || (typeof window !== 'undefined' && window.fetch);
if (!httpFetch) {
throw new Error('No valid fetcher implementation available');
}
options.enableIncrementalDelivery =
options.enableIncrementalDelivery !== false;
// simpler fetcher for schema requests
const simpleFetcher = createSimpleFetcher(options, httpFetch);
const httpFetcher = options.enableIncrementalDelivery
? createMultipartFetcher(options, httpFetch)
: simpleFetcher;
return async (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) {
if (
options.subscriptionUrl &&
!options.subscriptionUrl.startsWith('ws')
) {
const sseFetcher = await createSseFetcher({
url: options.subscriptionUrl,
});
return sseFetcher(graphQLParams);
}
const wsFetcher = await 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);
};
}