/
requestPipeline.ts
746 lines (658 loc) 路 25.9 KB
/
requestPipeline.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
import {
GraphQLSchema,
GraphQLFieldResolver,
specifiedRules,
DocumentNode,
getOperationAST,
ExecutionArgs,
GraphQLError,
GraphQLFormattedError,
validate as graphqlValidate,
parse as graphqlParse,
execute as graphqlExecute,
} from 'graphql';
import {
GraphQLExtension,
GraphQLExtensionStack,
enableGraphQLExtensions,
} from 'graphql-extensions';
import { DataSource } from 'apollo-datasource';
import { PersistedQueryOptions } from './graphqlOptions';
import {
symbolExecutionDispatcherWillResolveField,
enablePluginsForSchemaResolvers,
symbolUserFieldResolver,
} from "./utils/schemaInstrumentation"
import {
ApolloError,
fromGraphQLError,
SyntaxError,
ValidationError,
PersistedQueryNotSupportedError,
PersistedQueryNotFoundError,
formatApolloErrors,
} from 'apollo-server-errors';
import {
GraphQLRequest,
GraphQLResponse,
GraphQLRequestContext,
GraphQLExecutor,
GraphQLExecutionResult,
InvalidGraphQLRequestError,
ValidationRule,
WithRequired,
} from 'apollo-server-types';
import {
ApolloServerPlugin,
GraphQLRequestListener,
GraphQLRequestContextDidResolveSource,
GraphQLRequestContextExecutionDidStart,
GraphQLRequestContextResponseForOperation,
GraphQLRequestContextDidResolveOperation,
GraphQLRequestContextParsingDidStart,
GraphQLRequestContextValidationDidStart,
GraphQLRequestContextWillSendResponse,
GraphQLRequestContextDidEncounterErrors,
GraphQLRequestExecutionListener,
} from 'apollo-server-plugin-base';
import { Dispatcher } from './utils/dispatcher';
import {
InMemoryLRUCache,
KeyValueCache,
PrefixingKeyValueCache,
} from 'apollo-server-caching';
import { GraphQLParseOptions } from 'graphql-tools';
export {
GraphQLRequest,
GraphQLResponse,
GraphQLRequestContext,
InvalidGraphQLRequestError,
};
import createSHA from './utils/createSHA';
import { HttpQueryError } from './runHttpQuery';
export const APQ_CACHE_PREFIX = 'apq:';
function computeQueryHash(query: string) {
return createSHA('sha256')
.update(query)
.digest('hex');
}
export interface GraphQLRequestPipelineConfig<TContext> {
schema: GraphQLSchema;
rootValue?: ((document: DocumentNode) => any) | any;
validationRules?: ValidationRule[];
executor?: GraphQLExecutor;
fieldResolver?: GraphQLFieldResolver<any, TContext>;
dataSources?: () => DataSources<TContext>;
extensions?: Array<() => GraphQLExtension>;
persistedQueries?: PersistedQueryOptions;
formatError?: (error: GraphQLError) => GraphQLFormattedError;
formatResponse?: (
response: GraphQLResponse,
requestContext: GraphQLRequestContext<TContext>,
) => GraphQLResponse | null;
plugins?: ApolloServerPlugin[];
documentStore?: InMemoryLRUCache<DocumentNode>;
parseOptions?: GraphQLParseOptions;
}
export type DataSources<TContext> = {
[name: string]: DataSource<TContext>;
};
type Mutable<T> = { -readonly [P in keyof T]: T[P] };
/**
* We attach this symbol to the constructor of extensions to mark that we've
* already warned about the deprecation of the `graphql-extensions` API for that
* particular definition.
*/
const symbolExtensionDeprecationDone =
Symbol("apolloServerExtensionDeprecationDone");
export async function processGraphQLRequest<TContext>(
config: GraphQLRequestPipelineConfig<TContext>,
requestContext: Mutable<GraphQLRequestContext<TContext>>,
): Promise<GraphQLResponse> {
// For legacy reasons, this exported method may exist without a `logger` on
// the context. We'll need to make sure we account for that, even though
// all of our own machinery will certainly set it now.
const logger = requestContext.logger || console;
// If request context's `metrics` already exists, preserve it, but _ensure_ it
// exists there and shorthand it for use throughout this function.
const metrics = requestContext.metrics =
requestContext.metrics || Object.create(null);
const extensionStack = initializeExtensionStack();
(requestContext.context as any)._extensionStack = extensionStack;
const dispatcher = initializeRequestListenerDispatcher();
await initializeDataSources();
const request = requestContext.request;
let { query, extensions } = request;
let queryHash: string;
let persistedQueryCache: KeyValueCache | undefined;
metrics.persistedQueryHit = false;
metrics.persistedQueryRegister = false;
if (extensions && extensions.persistedQuery) {
// It looks like we've received a persisted query. Check if we
// support them.
if (!config.persistedQueries || !config.persistedQueries.cache) {
// We are returning to `runHttpQuery` to preserve legacy behavior while
// still delivering observability to the `didEncounterErrors` hook.
// This particular error will _not_ trigger `willSendResponse`.
// See comment on `emitErrorAndThrow` for more details.
return await emitErrorAndThrow(new PersistedQueryNotSupportedError());
} else if (extensions.persistedQuery.version !== 1) {
// We are returning to `runHttpQuery` to preserve legacy behavior while
// still delivering observability to the `didEncounterErrors` hook.
// This particular error will _not_ trigger `willSendResponse`.
// See comment on `emitErrorAndThrow` for more details.
return await emitErrorAndThrow(
new InvalidGraphQLRequestError('Unsupported persisted query version'));
}
// We'll store a reference to the persisted query cache so we can actually
// do the write at a later point in the request pipeline processing.
persistedQueryCache = config.persistedQueries.cache;
// This is a bit hacky, but if `config` came from direct use of the old
// apollo-server 1.0-style middleware (graphqlExpress etc, not via the
// ApolloServer class), it won't have been converted to
// PrefixingKeyValueCache yet.
if (!(persistedQueryCache instanceof PrefixingKeyValueCache)) {
persistedQueryCache = new PrefixingKeyValueCache(
persistedQueryCache,
APQ_CACHE_PREFIX,
);
}
queryHash = extensions.persistedQuery.sha256Hash;
if (query === undefined) {
query = await persistedQueryCache.get(queryHash);
if (query) {
metrics.persistedQueryHit = true;
} else {
// We are returning to `runHttpQuery` to preserve legacy behavior while
// still delivering observability to the `didEncounterErrors` hook.
// This particular error will _not_ trigger `willSendResponse`.
// See comment on `emitErrorAndThrow` for more details.
return await emitErrorAndThrow(new PersistedQueryNotFoundError());
}
} else {
const computedQueryHash = computeQueryHash(query);
// The provided hash must exactly match the SHA-256 hash of
// the query string. This prevents hash hijacking, where a
// new and potentially malicious query is associated with
// an existing hash.
if (queryHash !== computedQueryHash) {
// We are returning to `runHttpQuery` to preserve legacy behavior while
// still delivering observability to the `didEncounterErrors` hook.
// This particular error will _not_ trigger `willSendResponse`.
// See comment on `emitErrorAndThrow` for more details.
return await emitErrorAndThrow(
new InvalidGraphQLRequestError('provided sha does not match query'));
}
// We won't write to the persisted query cache until later.
// Deferring the writing gives plugins the ability to "win" from use of
// the cache, but also have their say in whether or not the cache is
// written to (by interrupting the request with an error).
metrics.persistedQueryRegister = true;
}
} else if (query) {
// FIXME: We'll compute the APQ query hash to use as our cache key for
// now, but this should be replaced with the new operation ID algorithm.
queryHash = computeQueryHash(query);
} else {
// We are returning to `runHttpQuery` to preserve legacy behavior
// while still delivering observability to the `didEncounterErrors` hook.
// This particular error will _not_ trigger `willSendResponse`.
// See comment on `emitErrorAndThrow` for more details.
return await emitErrorAndThrow(
new InvalidGraphQLRequestError('Must provide query string.'));
}
requestContext.queryHash = queryHash;
requestContext.source = query;
// Let the plugins know that we now have a STRING of what we hope will
// parse and validate into a document we can execute on. Unless we have
// retrieved this from our APQ cache, there's no guarantee that it is
// syntactically correct, so this string should not be trusted as a valid
// document until after it's parsed and validated.
await dispatcher.invokeHookAsync(
'didResolveSource',
requestContext as GraphQLRequestContextDidResolveSource<TContext>,
);
const requestDidEnd = extensionStack.requestDidStart({
request: request.http!,
queryString: request.query,
operationName: request.operationName,
variables: request.variables,
extensions: request.extensions,
context: requestContext.context,
persistedQueryHit: metrics.persistedQueryHit,
persistedQueryRegister: metrics.persistedQueryRegister,
requestContext: requestContext as WithRequired<
typeof requestContext,
'metrics' | 'queryHash'
>,
});
try {
// If we're configured with a document store (by default, we are), we'll
// utilize the operation's hash to lookup the AST from the previously
// parsed-and-validated operation. Failure to retrieve anything from the
// cache just means we're committed to doing the parsing and validation.
if (config.documentStore) {
try {
requestContext.document = await config.documentStore.get(queryHash);
} catch (err) {
logger.warn(
'An error occurred while attempting to read from the documentStore. '
+ (err && err.message) || err,
);
}
}
// If we still don't have a document, we'll need to parse and validate it.
// With success, we'll attempt to save it into the store for future use.
if (!requestContext.document) {
const parsingDidEnd = await dispatcher.invokeDidStartHook(
'parsingDidStart',
requestContext as GraphQLRequestContextParsingDidStart<TContext>,
);
try {
requestContext.document = parse(query, config.parseOptions);
parsingDidEnd();
} catch (syntaxError) {
parsingDidEnd(syntaxError);
return await sendErrorResponse(syntaxError, SyntaxError);
}
const validationDidEnd = await dispatcher.invokeDidStartHook(
'validationDidStart',
requestContext as GraphQLRequestContextValidationDidStart<TContext>,
);
const validationErrors = validate(requestContext.document);
if (validationErrors.length === 0) {
validationDidEnd();
} else {
validationDidEnd(validationErrors);
return await sendErrorResponse(validationErrors, ValidationError);
}
if (config.documentStore) {
// The underlying cache store behind the `documentStore` returns a
// `Promise` which is resolved (or rejected), eventually, based on the
// success or failure (respectively) of the cache save attempt. While
// it's certainly possible to `await` this `Promise`, we don't care about
// whether or not it's successful at this point. We'll instead proceed
// to serve the rest of the request and just hope that this works out.
// If it doesn't work, the next request will have another opportunity to
// try again. Errors will surface as warnings, as appropriate.
//
// While it shouldn't normally be necessary to wrap this `Promise` in a
// `Promise.resolve` invocation, it seems that the underlying cache store
// is returning a non-native `Promise` (e.g. Bluebird, etc.).
Promise.resolve(
config.documentStore.set(queryHash, requestContext.document),
).catch(err =>
logger.warn(
'Could not store validated document. ' +
(err && err.message) || err
)
);
}
}
// FIXME: If we want to guarantee an operation has been set when invoking
// `willExecuteOperation` and executionDidStart`, we need to throw an
// error here and not leave this to `buildExecutionContext` in
// `graphql-js`.
const operation = getOperationAST(
requestContext.document,
request.operationName,
);
requestContext.operation = operation || undefined;
// We'll set `operationName` to `null` for anonymous operations.
requestContext.operationName =
(operation && operation.name && operation.name.value) || null;
try {
await dispatcher.invokeHookAsync(
'didResolveOperation',
requestContext as GraphQLRequestContextDidResolveOperation<TContext>,
);
} catch (err) {
// XXX: The HttpQueryError is special-cased here because we currently
// depend on `throw`-ing an error from the `didResolveOperation` hook
// we've implemented in `runHttpQuery.ts`'s `checkOperationPlugin`:
// https://git.io/fj427. This could be perceived as a feature, but
// for the time-being this just maintains existing behavior for what
// happens when `throw`-ing an `HttpQueryError` in `didResolveOperation`.
if (err instanceof HttpQueryError) {
// In order to report this error reliably to the request pipeline, we'll
// have to regenerate it with the original error message and stack for
// the purposes of the `didEncounterErrors` life-cycle hook (which
// expects `GraphQLError`s), but still throw the `HttpQueryError`, so
// the appropriate status code is enforced by `runHttpQuery.ts`.
const graphqlError = new GraphQLError(err.message);
graphqlError.stack = err.stack;
await didEncounterErrors([graphqlError]);
throw err;
}
return await sendErrorResponse(err);
}
// Now that we've gone through the pre-execution phases of the request
// pipeline, and given plugins appropriate ability to object (by throwing
// an error) and not actually write, we'll write to the cache if it was
// determined earlier in the request pipeline that we should do so.
if (metrics.persistedQueryRegister && persistedQueryCache) {
// While it shouldn't normally be necessary to wrap this `Promise` in a
// `Promise.resolve` invocation, it seems that the underlying cache store
// is returning a non-native `Promise` (e.g. Bluebird, etc.).
Promise.resolve(
persistedQueryCache.set(
queryHash,
query,
config.persistedQueries &&
typeof config.persistedQueries.ttl !== 'undefined'
? {
ttl: config.persistedQueries.ttl,
}
: Object.create(null),
),
).catch(logger.warn);
}
let response: GraphQLResponse | null = await dispatcher.invokeHooksUntilNonNull(
'responseForOperation',
requestContext as GraphQLRequestContextResponseForOperation<TContext>,
);
if (response == null) {
// This execution dispatcher code is duplicated in `pluginTestHarness`
// right now.
const executionListeners: GraphQLRequestExecutionListener<TContext>[] = [];
dispatcher.invokeHookSync(
'executionDidStart',
requestContext as GraphQLRequestContextExecutionDidStart<TContext>,
).forEach(executionListener => {
if (typeof executionListener === 'function') {
executionListeners.push({
executionDidEnd: executionListener,
});
} else if (typeof executionListener === 'object') {
executionListeners.push(executionListener);
}
});
const executionDispatcher = new Dispatcher(executionListeners);
// Create a callback that will trigger the execution dispatcher's
// `willResolveField` hook. We will attach this to the context on a
// symbol so it can be invoked by our `wrapField` method during execution.
const invokeWillResolveField: GraphQLRequestExecutionListener<
TContext
>['willResolveField'] = (...args) =>
executionDispatcher.invokeDidStartHook('willResolveField', ...args);
Object.defineProperty(
requestContext.context,
symbolExecutionDispatcherWillResolveField,
{ value: invokeWillResolveField }
);
// If the user has provided a custom field resolver, we will attach
// it to the context so we can still invoke it after we've wrapped the
// fields with `wrapField` within `enablePluginsForSchemaResolvers` of
// the `schemaInstrumentation` module.
if (config.fieldResolver) {
Object.defineProperty(
requestContext.context,
symbolUserFieldResolver,
{ value: config.fieldResolver }
);
}
// If the schema is already enabled, this is a no-op. Otherwise, the
// schema will be augmented so it is able to invoke willResolveField.
enablePluginsForSchemaResolvers(config.schema);
try {
const result = await execute(
requestContext as GraphQLRequestContextExecutionDidStart<TContext>,
);
if (result.errors) {
await didEncounterErrors(result.errors);
}
response = {
...result,
errors: result.errors ? formatErrors(result.errors) : undefined,
};
executionDispatcher.reverseInvokeHookSync("executionDidEnd");
} catch (executionError) {
executionDispatcher.reverseInvokeHookSync("executionDidEnd", executionError);
return await sendErrorResponse(executionError);
}
}
const formattedExtensions = extensionStack.format();
if (Object.keys(formattedExtensions).length > 0) {
response.extensions = formattedExtensions;
}
if (config.formatResponse) {
const formattedResponse: GraphQLResponse | null = config.formatResponse(
response,
requestContext,
);
if (formattedResponse != null) {
response = formattedResponse;
}
}
return sendResponse(response);
} finally {
requestDidEnd();
}
function parse(
query: string,
parseOptions?: GraphQLParseOptions,
): DocumentNode {
const parsingDidEnd = extensionStack.parsingDidStart({
queryString: query,
});
try {
return graphqlParse(query, parseOptions);
} finally {
parsingDidEnd();
}
}
function validate(document: DocumentNode): ReadonlyArray<GraphQLError> {
let rules = specifiedRules;
if (config.validationRules) {
rules = rules.concat(config.validationRules);
}
const validationDidEnd = extensionStack.validationDidStart();
try {
return graphqlValidate(config.schema, document, rules);
} finally {
validationDidEnd();
}
}
async function execute(
requestContext: GraphQLRequestContextExecutionDidStart<TContext>,
): Promise<GraphQLExecutionResult> {
const { request, document } = requestContext;
const executionArgs: ExecutionArgs = {
schema: config.schema,
document,
rootValue:
typeof config.rootValue === 'function'
? config.rootValue(document)
: config.rootValue,
contextValue: requestContext.context,
variableValues: request.variables,
operationName: request.operationName,
fieldResolver: config.fieldResolver,
};
const executionDidEnd = extensionStack.executionDidStart({
executionArgs,
});
try {
if (config.executor) {
// XXX Nothing guarantees that the only errors thrown or returned
// in result.errors are GraphQLErrors, even though other code
// (eg ApolloServerPluginUsageReporting) assumes that.
return await config.executor(requestContext);
} else {
return await graphqlExecute(executionArgs);
}
} finally {
executionDidEnd();
}
}
async function sendResponse(
response: GraphQLResponse,
): Promise<GraphQLResponse> {
// We override errors, data, and extensions with the passed in response,
// but keep other properties (like http)
requestContext.response = extensionStack.willSendResponse({
graphqlResponse: {
...requestContext.response,
errors: response.errors,
data: response.data,
extensions: response.extensions,
},
context: requestContext.context,
}).graphqlResponse;
await dispatcher.invokeHookAsync(
'willSendResponse',
requestContext as GraphQLRequestContextWillSendResponse<TContext>,
);
return requestContext.response!;
}
/**
* HEREIN LIE LEGACY COMPATIBILITY
*
* DO NOT PERPETUATE THE USE OF THIS METHOD IN NEWLY INTRODUCED CODE.
*
* Report an error via `didEncounterErrors` and then `throw` it again,
* ENTIRELY BYPASSING the rest of the request pipeline and returning
* control to `runHttpQuery.ts`.
*
* Any number of other life-cycle events may not be invoked in this case.
*
* Prior to the introduction of this function, some errors were being thrown
* within the request pipeline and going directly to handling within
* the `runHttpQuery.ts` module, rather than first being reported to the
* plugin API's `didEncounterErrors` life-cycle hook (where they are to be
* expected!).
*
* @param error The error to report to the request pipeline plugins prior
* to being thrown.
*
* @throws
*
*/
async function emitErrorAndThrow(error: GraphQLError): Promise<never> {
await didEncounterErrors([error]);
throw error;
}
async function didEncounterErrors(errors: ReadonlyArray<GraphQLError>) {
requestContext.errors = errors;
extensionStack.didEncounterErrors(errors);
return await dispatcher.invokeHookAsync(
'didEncounterErrors',
requestContext as GraphQLRequestContextDidEncounterErrors<TContext>,
);
}
async function sendErrorResponse(
errorOrErrors: ReadonlyArray<GraphQLError> | GraphQLError,
errorClass?: typeof ApolloError,
) {
// If a single error is passed, it should still be encapsulated in an array.
const errors = Array.isArray(errorOrErrors)
? errorOrErrors
: [errorOrErrors];
await didEncounterErrors(errors);
return sendResponse({
errors: formatErrors(
errors.map(err =>
fromGraphQLError(
err,
errorClass && {
errorClass,
},
),
),
),
});
}
function formatErrors(
errors: ReadonlyArray<GraphQLError>,
): ReadonlyArray<GraphQLFormattedError> {
return formatApolloErrors(errors, {
formatter: config.formatError,
debug: requestContext.debug,
});
}
function initializeRequestListenerDispatcher(): Dispatcher<
GraphQLRequestListener<TContext>
> {
const requestListeners: GraphQLRequestListener<TContext>[] = [];
if (config.plugins) {
for (const plugin of config.plugins) {
if (!plugin.requestDidStart) continue;
const listener = plugin.requestDidStart(requestContext);
if (listener) {
requestListeners.push(listener);
}
}
}
return new Dispatcher(requestListeners);
}
function initializeExtensionStack(): GraphQLExtensionStack<TContext> {
if (config.extensions?.length) {
// graphql-extensions adds some overhead to field resolvers.
// Only enable extensions when at least 1 extension has been provided
enableGraphQLExtensions(config.schema);
}
// If custom extension factories were provided, create per-request extension
// objects.
const extensions = config.extensions ? config.extensions.map(f => f()) : [];
// Warn about usage of (deprecated) `graphql-extensions` implementations.
// Since extensions are often provided as factory functions which
// instantiate an extension on each request, we'll attach a symbol to the
// constructor after we've warned to ensure that we don't do it on each
// request. Another option here might be to keep a `Map` of constructor
// instances within this module, but I hope this will do the trick.
const hasOwn = Object.prototype.hasOwnProperty;
extensions.forEach((extension) => {
// Using `hasOwn` just in case there is a user-land `hasOwnProperty`
// defined on the `constructor` object.
if (
!extension.constructor ||
hasOwn.call(extension.constructor, symbolExtensionDeprecationDone)
) {
return;
}
Object.defineProperty(
extension.constructor,
symbolExtensionDeprecationDone,
{ value: true }
);
const extensionName = extension.constructor.name;
logger.warn(
'[deprecated] ' +
(extensionName
? 'A "' + extensionName + '" '
: 'An anonymous extension ') +
'was defined within the "extensions" configuration for ' +
'Apollo Server. The API on which this extension is built ' +
'("graphql-extensions") is being deprecated in the next major ' +
'version of Apollo Server in favor of the new plugin API. See ' +
'https://go.apollo.dev/s/plugins for the documentation on how ' +
'these plugins are to be defined and used.',
);
});
return new GraphQLExtensionStack(extensions);
}
async function initializeDataSources() {
if (config.dataSources) {
const context = requestContext.context;
const dataSources = config.dataSources();
const initializers: any[] = [];
for (const dataSource of Object.values(dataSources)) {
if (dataSource.initialize) {
initializers.push(
dataSource.initialize({
context,
cache: requestContext.cache,
})
);
}
}
await Promise.all(initializers);
if ('dataSources' in context) {
throw new Error(
'Please use the dataSources config option instead of putting dataSources on the context yourself.',
);
}
(context as any).dataSources = dataSources;
}
}
}