/
index.ts
147 lines (126 loc) · 4.34 KB
/
index.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import { print, IntrospectionOptions, DocumentNode, GraphQLResolveInfo } from 'graphql';
import {
SchemaPointerSingle,
Source,
DocumentLoader,
SingleFileOptions,
observableToAsyncIterable,
ExecutionResult,
} from '@graphql-tools/utils';
import { isWebUri } from 'valid-url';
import { fetch as crossFetch } from 'cross-fetch';
import { introspectSchema, makeRemoteExecutableSchema, IMakeRemoteExecutableSchemaOptions } from '@graphql-tools/wrap';
import { SubscriptionClient } from 'subscriptions-transport-ws';
import { w3cwebsocket } from 'websocket';
export type FetchFn = typeof import('cross-fetch').fetch;
type Headers = Record<string, string> | Array<Record<string, string>>;
export interface LoadFromUrlOptions extends SingleFileOptions, Partial<IntrospectionOptions> {
headers?: Headers;
customFetch?: FetchFn | string;
method?: 'GET' | 'POST';
enableSubscriptions?: boolean;
webSocketImpl?: typeof w3cwebsocket | string;
useGETForQueries?: boolean;
}
export class UrlLoader implements DocumentLoader<LoadFromUrlOptions> {
loaderId(): string {
return 'url';
}
async canLoad(pointer: SchemaPointerSingle, options: LoadFromUrlOptions): Promise<boolean> {
return this.canLoadSync(pointer, options);
}
canLoadSync(pointer: SchemaPointerSingle, _options: LoadFromUrlOptions): boolean {
return !!isWebUri(pointer);
}
async load(pointer: SchemaPointerSingle, options: LoadFromUrlOptions): Promise<Source> {
let headers = {};
let fetch = crossFetch;
let defaultMethod: 'GET' | 'POST' = 'POST';
let webSocketImpl = w3cwebsocket;
if (options) {
if (Array.isArray(options.headers)) {
headers = options.headers.reduce((prev: any, v: any) => ({ ...prev, ...v }), {});
} else if (typeof options.headers === 'object') {
headers = options.headers;
}
if (options.customFetch) {
if (typeof options.customFetch === 'string') {
const [moduleName, fetchFnName] = options.customFetch.split('#');
fetch = await import(moduleName).then(module => (fetchFnName ? module[fetchFnName] : module));
}
}
if (options.webSocketImpl) {
if (typeof options.webSocketImpl === 'string') {
const [moduleName, webSocketImplName] = options.webSocketImpl.split('#');
webSocketImpl = await import(moduleName).then(module =>
webSocketImplName ? module[webSocketImplName] : module
);
}
}
if (options.method) {
defaultMethod = options.method;
}
}
const extraHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json',
...headers,
};
const HTTP_URL = pointer.replace('ws:', 'http:').replace('wss:', 'https:');
const executor = async ({
document,
variables,
info,
}: {
document: DocumentNode;
variables: any;
info: GraphQLResolveInfo;
}) => {
let method = defaultMethod;
if (options.useGETForQueries && info.operation.operation === 'query') {
method = 'GET';
}
const fetchResult = await fetch(HTTP_URL, {
method,
...(method === 'POST'
? {
body: JSON.stringify({ query: print(document), variables }),
}
: {}),
headers: extraHeaders,
});
return fetchResult.json();
};
const schema = await introspectSchema(executor);
const remoteExecutableSchemaOptions: IMakeRemoteExecutableSchemaOptions = {
schema,
executor,
};
if (options.enableSubscriptions) {
const WS_URL = pointer.replace('http:', 'ws:').replace('https:', 'wss:');
const subscriptionClient = new SubscriptionClient(WS_URL, {}, webSocketImpl);
remoteExecutableSchemaOptions.subscriber = async <TReturn, TArgs>({
document,
variables,
}: {
document: DocumentNode;
variables: TArgs;
}) => {
return observableToAsyncIterable(
subscriptionClient.request({
query: document,
variables,
})
) as AsyncIterator<ExecutionResult<TReturn>>;
};
}
const remoteExecutableSchema = makeRemoteExecutableSchema(remoteExecutableSchemaOptions);
return {
location: pointer,
schema: remoteExecutableSchema,
};
}
loadSync(): never {
throw new Error('Loader Url has no sync mode');
}
}