-
-
Notifications
You must be signed in to change notification settings - Fork 796
/
index.ts
280 lines (253 loc) · 8.33 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/* eslint-disable no-case-declarations */
import { print, IntrospectionOptions, DocumentNode, GraphQLResolveInfo, Kind, parse, buildASTSchema } 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 { AsyncExecutor, Subscriber } from '@graphql-tools/delegate';
import { introspectSchema, wrapSchema } 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>>;
/**
* Additional options for loading from a URL
*/
export interface LoadFromUrlOptions extends SingleFileOptions, Partial<IntrospectionOptions> {
/**
* Additional headers to include when querying the original schema
*/
headers?: Headers;
/**
* A custom `fetch` implementation to use when querying the original schema.
* Defaults to `cross-fetch`
*/
customFetch?: FetchFn | string;
/**
* HTTP method to use when querying the original schema.
*/
method?: 'GET' | 'POST';
/**
* Whether to enable subscriptions on the loaded schema
*/
enableSubscriptions?: boolean;
/**
* Custom WebSocket implementation used by the loaded schema if subscriptions
* are enabled
*/
webSocketImpl?: typeof w3cwebsocket | string;
/**
* Whether to use the GET HTTP method for queries when querying the original schema
*/
useGETForQueries?: boolean;
}
/**
* This loader loads a schema from a URL. The loaded schema is a fully-executable,
* remote schema since it's created using [@graphql-tools/wrap](/docs/remote-schemas).
*
* ```
* const schema = await loadSchema('http://localhost:3000/graphql', {
* loaders: [
* new UrlLoader(),
* ]
* });
* ```
*/
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);
}
buildAsyncExecutor({
pointer,
fetch,
extraHeaders,
defaultMethod,
useGETForQueries,
}: {
pointer: string;
fetch: typeof crossFetch;
extraHeaders: any;
defaultMethod: 'GET' | 'POST';
useGETForQueries: boolean;
}): AsyncExecutor {
const HTTP_URL = switchProtocols(pointer, {
wss: 'https',
ws: 'http',
});
return async ({ document, variables }: { document: DocumentNode; variables: any; info: GraphQLResolveInfo }) => {
let method = defaultMethod;
if (useGETForQueries) {
method = 'GET';
for (const definition of document.definitions) {
if (definition.kind === Kind.OPERATION_DEFINITION) {
if (definition.operation !== 'query') {
method = defaultMethod;
}
}
}
}
let fetchResult: Response;
const query = print(document);
switch (method) {
case 'GET':
const urlObj = new URL(HTTP_URL);
urlObj.searchParams.set('query', query);
if (variables && Object.keys(variables).length > 0) {
urlObj.searchParams.set('variables', JSON.stringify(variables));
}
const finalUrl = urlObj.toString();
fetchResult = await fetch(finalUrl, {
method: 'GET',
headers: extraHeaders,
});
break;
case 'POST':
fetchResult = await fetch(HTTP_URL, {
method: 'POST',
body: JSON.stringify({
query,
variables,
}),
headers: extraHeaders,
});
break;
}
return fetchResult.json();
};
}
buildSubscriber(pointer: string, webSocketImpl: typeof w3cwebsocket): Subscriber {
const WS_URL = switchProtocols(pointer, {
https: 'wss',
http: 'ws',
});
const subscriptionClient = new SubscriptionClient(WS_URL, {}, webSocketImpl);
return async <TReturn, TArgs>({ document, variables }: { document: DocumentNode; variables: TArgs }) => {
return observableToAsyncIterable(
subscriptionClient.request({
query: document,
variables,
})
) as AsyncIterableIterator<ExecutionResult<TReturn>>;
};
}
private async getFetch(options: LoadFromUrlOptions, defaultMethod: 'GET' | 'POST') {
let headers = {};
let fetch = crossFetch;
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));
} else {
fetch = options.customFetch;
}
}
if (options.webSocketImpl) {
if (typeof options.webSocketImpl === 'string') {
const [moduleName, webSocketImplName] = options.webSocketImpl.split('#');
webSocketImpl = await import(moduleName).then(module =>
webSocketImplName ? module[webSocketImplName] : module
);
} else {
webSocketImpl = options.webSocketImpl;
}
}
if (options.method) {
defaultMethod = options.method;
}
}
return { headers, defaultMethod, fetch, webSocketImpl };
}
async getExecutorAndSubscriber(
pointer: SchemaPointerSingle,
options: LoadFromUrlOptions
): Promise<{ executor: AsyncExecutor; subscriber: Subscriber }> {
const { headers, defaultMethod, fetch, webSocketImpl } = await this.getFetch(options, 'POST');
const extraHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json',
...headers,
};
const executor = this.buildAsyncExecutor({
pointer,
fetch,
extraHeaders,
defaultMethod,
useGETForQueries: options.useGETForQueries,
});
let subscriber: Subscriber;
if (options.enableSubscriptions) {
subscriber = this.buildSubscriber(pointer, webSocketImpl);
}
return {
executor,
subscriber,
};
}
async getSubschemaConfig(pointer: SchemaPointerSingle, options: LoadFromUrlOptions) {
const { executor, subscriber } = await this.getExecutorAndSubscriber(pointer, options);
return {
schema: await introspectSchema(executor, undefined, options as IntrospectionOptions),
executor,
subscriber,
};
}
async handleSDL(pointer: SchemaPointerSingle, options: LoadFromUrlOptions) {
const { fetch, defaultMethod, headers } = await this.getFetch(options, 'GET');
const response = await fetch(pointer, {
method: defaultMethod,
headers,
});
const schemaString = await response.text();
const document = parse(schemaString, options);
const schema = buildASTSchema(document, options);
return {
document,
schema,
};
}
async load(pointer: SchemaPointerSingle, options: LoadFromUrlOptions): Promise<Source> {
if (pointer.endsWith('.graphql')) {
const { document, schema } = await this.handleSDL(pointer, options);
return {
location: pointer,
document,
schema,
};
}
const subschemaConfig = await this.getSubschemaConfig(pointer, options);
const remoteExecutableSchema = wrapSchema(subschemaConfig);
return {
location: pointer,
schema: remoteExecutableSchema,
};
}
loadSync(): never {
throw new Error('Loader Url has no sync mode');
}
}
function switchProtocols(pointer: string, protocolMap: Record<string, string>): string {
const protocols: [string, string][] = Object.keys(protocolMap).map(source => [source, protocolMap[source]]);
return protocols.reduce(
(prev, [source, target]) => prev.replace(`${source}://`, `${target}://`).replace(`${source}:\\`, `${target}:\\`),
pointer
);
}