-
-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathschemaGenerator.ts
812 lines (729 loc) · 24.5 KB
/
schemaGenerator.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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
// Generates a schema for graphql-js given a shorthand schema
// TODO: document each function clearly in the code: what arguments it accepts
// and what it outputs.
// TODO: we should refactor this file, rename it to makeExecutableSchema, and move
// a bunch of utility functions into a separate utitlities folder, one file per function.
import {
GraphQLEnumType,
DocumentNode,
parse,
print,
DefinitionNode,
defaultFieldResolver,
buildASTSchema,
extendSchema,
GraphQLScalarType,
getNamedType,
GraphQLObjectType,
GraphQLSchema,
GraphQLResolveInfo,
GraphQLField,
GraphQLFieldResolver,
GraphQLType,
GraphQLInterfaceType,
GraphQLFieldMap,
GraphQLUnionType,
} from 'graphql';
import {
IExecutableSchemaDefinition,
ILogger,
IResolvers,
ITypeDefinitions,
ITypedef,
IFieldIteratorFn,
IConnectors,
IConnector,
IConnectorCls,
IResolverValidationOptions,
IDirectiveResolvers,
UnitOrList,
GraphQLParseOptions,
IAddResolveFunctionsToSchemaOptions,
} from './Interfaces';
import { SchemaDirectiveVisitor } from './schemaVisitor';
import { deprecated } from 'deprecated-decorator';
import mergeDeep from './mergeDeep';
// @schemaDefinition: A GraphQL type schema in shorthand
// @resolvers: Definitions for resolvers to be merged with schema
class SchemaError extends Error {
public message: string;
constructor(message: string) {
super(message);
this.message = message;
Error.captureStackTrace(this, this.constructor);
}
}
// type definitions can be a string or an array of strings.
function _generateSchema(
typeDefinitions: ITypeDefinitions,
resolveFunctions: UnitOrList<IResolvers>,
logger: ILogger,
// TODO: rename to allowUndefinedInResolve to be consistent
allowUndefinedInResolve: boolean,
resolverValidationOptions: IResolverValidationOptions,
parseOptions: GraphQLParseOptions,
inheritResolversFromInterfaces: boolean
) {
if (typeof resolverValidationOptions !== 'object') {
throw new SchemaError(
'Expected `resolverValidationOptions` to be an object',
);
}
if (!typeDefinitions) {
throw new SchemaError('Must provide typeDefs');
}
if (!resolveFunctions) {
throw new SchemaError('Must provide resolvers');
}
const resolvers = Array.isArray(resolveFunctions)
? resolveFunctions
.filter(resolverObj => typeof resolverObj === 'object')
.reduce(mergeDeep, {})
: resolveFunctions;
// TODO: check that typeDefinitions is either string or array of strings
const schema = buildSchemaFromTypeDefinitions(typeDefinitions, parseOptions);
addResolveFunctionsToSchema({ schema, resolvers, resolverValidationOptions, inheritResolversFromInterfaces });
assertResolveFunctionsPresent(schema, resolverValidationOptions);
if (!allowUndefinedInResolve) {
addCatchUndefinedToSchema(schema);
}
if (logger) {
addErrorLoggingToSchema(schema, logger);
}
return schema;
}
function makeExecutableSchema<TContext = any>({
typeDefs,
resolvers = {},
connectors,
logger,
allowUndefinedInResolve = true,
resolverValidationOptions = {},
directiveResolvers = null,
schemaDirectives = null,
parseOptions = {},
inheritResolversFromInterfaces = false
}: IExecutableSchemaDefinition<TContext>) {
const jsSchema = _generateSchema(
typeDefs,
resolvers,
logger,
allowUndefinedInResolve,
resolverValidationOptions,
parseOptions,
inheritResolversFromInterfaces
);
if (typeof resolvers['__schema'] === 'function') {
// TODO a bit of a hack now, better rewrite generateSchema to attach it there.
// not doing that now, because I'd have to rewrite a lot of tests.
addSchemaLevelResolveFunction(jsSchema, resolvers[
'__schema'
] as GraphQLFieldResolver<any, any>);
}
if (connectors) {
// connectors are optional, at least for now. That means you can just import them in the resolve
// function if you want.
attachConnectorsToContext(jsSchema, connectors);
}
if (directiveResolvers) {
attachDirectiveResolvers(jsSchema, directiveResolvers);
}
if (schemaDirectives) {
SchemaDirectiveVisitor.visitSchemaDirectives(
jsSchema,
schemaDirectives,
);
}
return jsSchema;
}
function isDocumentNode(
typeDefinitions: ITypeDefinitions,
): typeDefinitions is DocumentNode {
return (<DocumentNode>typeDefinitions).kind !== undefined;
}
function uniq(array: Array<any>): Array<any> {
return array.reduce((accumulator, currentValue) => {
return accumulator.indexOf(currentValue) === -1
? [...accumulator, currentValue]
: accumulator;
}, []);
}
function concatenateTypeDefs(
typeDefinitionsAry: ITypedef[],
calledFunctionRefs = [] as any,
): string {
let resolvedTypeDefinitions: string[] = [];
typeDefinitionsAry.forEach((typeDef: ITypedef) => {
if (isDocumentNode(typeDef)) {
typeDef = print(typeDef);
}
if (typeof typeDef === 'function') {
if (calledFunctionRefs.indexOf(typeDef) === -1) {
calledFunctionRefs.push(typeDef);
resolvedTypeDefinitions = resolvedTypeDefinitions.concat(
concatenateTypeDefs(typeDef(), calledFunctionRefs),
);
}
} else if (typeof typeDef === 'string') {
resolvedTypeDefinitions.push(typeDef.trim());
} else {
const type = typeof typeDef;
throw new SchemaError(
`typeDef array must contain only strings and functions, got ${type}`,
);
}
});
return uniq(resolvedTypeDefinitions.map(x => x.trim())).join('\n');
}
function buildSchemaFromTypeDefinitions(
typeDefinitions: ITypeDefinitions,
parseOptions?: GraphQLParseOptions,
): GraphQLSchema {
// TODO: accept only array here, otherwise interfaces get confusing.
let myDefinitions = typeDefinitions;
let astDocument: DocumentNode;
if (isDocumentNode(typeDefinitions)) {
astDocument = typeDefinitions;
} else if (typeof myDefinitions !== 'string') {
if (!Array.isArray(myDefinitions)) {
const type = typeof myDefinitions;
throw new SchemaError(
`typeDefs must be a string, array or schema AST, got ${type}`,
);
}
myDefinitions = concatenateTypeDefs(myDefinitions);
}
if (typeof myDefinitions === 'string') {
astDocument = parse(myDefinitions, parseOptions);
}
const backcompatOptions = { commentDescriptions: true };
// TODO fix types https://github.com/apollographql/graphql-tools/issues/542
let schema: GraphQLSchema = (buildASTSchema as any)(
astDocument,
backcompatOptions,
);
const extensionsAst = extractExtensionDefinitions(astDocument);
if (extensionsAst.definitions.length > 0) {
// TODO fix types https://github.com/apollographql/graphql-tools/issues/542
schema = (extendSchema as any)(schema, extensionsAst, backcompatOptions);
}
return schema;
}
// This was changed in graphql@0.12
// See https://github.com/apollographql/graphql-tools/pull/541
// TODO fix types https://github.com/apollographql/graphql-tools/issues/542
const oldTypeExtensionDefinitionKind = 'TypeExtensionDefinition';
const newExtensionDefinitionKind = 'ObjectTypeExtension';
const interfaceExtensionDefinitionKind = 'InterfaceTypeExtension';
export function extractExtensionDefinitions(ast: DocumentNode) {
const extensionDefs = ast.definitions.filter(
(def: DefinitionNode) =>
def.kind === oldTypeExtensionDefinitionKind ||
(def.kind as any) === newExtensionDefinitionKind ||
(def.kind as any) === interfaceExtensionDefinitionKind,
);
return Object.assign({}, ast, {
definitions: extensionDefs,
});
}
function forEachField(schema: GraphQLSchema, fn: IFieldIteratorFn): void {
const typeMap = schema.getTypeMap();
Object.keys(typeMap).forEach(typeName => {
const type = typeMap[typeName];
// TODO: maybe have an option to include these?
if (
!getNamedType(type).name.startsWith('__') &&
type instanceof GraphQLObjectType
) {
const fields = type.getFields();
Object.keys(fields).forEach(fieldName => {
const field = fields[fieldName];
fn(field, typeName, fieldName);
});
}
});
}
// takes a GraphQL-JS schema and an object of connectors, then attaches
// the connectors to the context by wrapping each query or mutation resolve
// function with a function that attaches connectors if they don't exist.
// attaches connectors only once to make sure they are singletons
const attachConnectorsToContext = deprecated<Function>(
{
version: '0.7.0',
url: 'https://github.com/apollostack/graphql-tools/issues/140',
},
function(schema: GraphQLSchema, connectors: IConnectors): void {
if (!schema || !(schema instanceof GraphQLSchema)) {
throw new Error(
'schema must be an instance of GraphQLSchema. ' +
'This error could be caused by installing more than one version of GraphQL-JS',
);
}
if (typeof connectors !== 'object') {
const connectorType = typeof connectors;
throw new Error(
`Expected connectors to be of type object, got ${connectorType}`,
);
}
if (Object.keys(connectors).length === 0) {
throw new Error('Expected connectors to not be an empty object');
}
if (Array.isArray(connectors)) {
throw new Error('Expected connectors to be of type object, got Array');
}
if (schema['_apolloConnectorsAttached']) {
throw new Error(
'Connectors already attached to context, cannot attach more than once',
);
}
schema['_apolloConnectorsAttached'] = true;
const attachconnectorFn: GraphQLFieldResolver<any, any> = (
root: any,
args: { [key: string]: any },
ctx: any,
) => {
if (typeof ctx !== 'object') {
// if in any way possible, we should throw an error when the attachconnectors
// function is called, not when a query is executed.
const contextType = typeof ctx;
throw new Error(
`Cannot attach connector because context is not an object: ${contextType}`,
);
}
if (typeof ctx.connectors === 'undefined') {
ctx.connectors = {};
}
Object.keys(connectors).forEach(connectorName => {
let connector: IConnector = connectors[connectorName];
if (!!connector.prototype) {
ctx.connectors[connectorName] = new (<IConnectorCls>connector)(ctx);
} else {
throw new Error(`Connector must be a function or an class`);
}
});
return root;
};
addSchemaLevelResolveFunction(schema, attachconnectorFn);
},
);
// wraps all resolve functions of query, mutation or subscription fields
// with the provided function to simulate a root schema level resolve funciton
function addSchemaLevelResolveFunction(
schema: GraphQLSchema,
fn: GraphQLFieldResolver<any, any>,
): void {
// TODO test that schema is a schema, fn is a function
const rootTypes = [
schema.getQueryType(),
schema.getMutationType(),
schema.getSubscriptionType(),
].filter(x => !!x);
rootTypes.forEach(type => {
// XXX this should run at most once per request to simulate a true root resolver
// for graphql-js this is an approximation that works with queries but not mutations
const rootResolveFn = runAtMostOncePerRequest(fn);
const fields = type.getFields();
Object.keys(fields).forEach(fieldName => {
// XXX if the type is a subscription, a same query AST will be ran multiple times so we
// deactivate here the runOnce if it's a subscription. This may not be optimal though...
if (type === schema.getSubscriptionType()) {
fields[fieldName].resolve = wrapResolver(fields[fieldName].resolve, fn);
} else {
fields[fieldName].resolve = wrapResolver(
fields[fieldName].resolve,
rootResolveFn,
);
}
});
});
}
function getFieldsForType(type: GraphQLType): GraphQLFieldMap<any, any> {
if (
type instanceof GraphQLObjectType ||
type instanceof GraphQLInterfaceType
) {
return type.getFields();
} else {
return undefined;
}
}
function addResolveFunctionsToSchema(
options: IAddResolveFunctionsToSchemaOptions|GraphQLSchema,
legacyInputResolvers?: IResolvers,
legacyInputValidationOptions?: IResolverValidationOptions) {
if (options instanceof GraphQLSchema) {
console.warn('The addResolveFunctionsToSchema function takes named options now; see IAddResolveFunctionsToSchemaOptions');
options = {
schema: options,
resolvers: legacyInputResolvers,
resolverValidationOptions: legacyInputValidationOptions
};
}
const {
schema,
resolvers: inputResolvers,
resolverValidationOptions = {},
inheritResolversFromInterfaces = false
} = options;
const {
allowResolversNotInSchema = false,
requireResolversForResolveType,
} = resolverValidationOptions;
const resolvers = inheritResolversFromInterfaces
? extendResolversFromInterfaces(schema, inputResolvers)
: inputResolvers;
Object.keys(resolvers).forEach(typeName => {
const type = schema.getType(typeName);
if (!type && typeName !== '__schema') {
if (allowResolversNotInSchema) {
return;
}
throw new SchemaError(
`"${typeName}" defined in resolvers, but not in schema`,
);
}
Object.keys(resolvers[typeName]).forEach(fieldName => {
if (fieldName.startsWith('__')) {
// this is for isTypeOf and resolveType and all the other stuff.
type[fieldName.substring(2)] = resolvers[typeName][fieldName];
return;
}
if (type instanceof GraphQLScalarType) {
type[fieldName] = resolvers[typeName][fieldName];
return;
}
if (type instanceof GraphQLEnumType) {
if (!type.getValue(fieldName)) {
throw new SchemaError(
`${typeName}.${fieldName} was defined in resolvers, but enum is not in schema`,
);
}
type.getValue(fieldName)['value'] =
resolvers[typeName][fieldName];
return;
}
// object type
const fields = getFieldsForType(type);
if (!fields) {
if (allowResolversNotInSchema) {
return;
}
throw new SchemaError(
`${typeName} was defined in resolvers, but it's not an object`,
);
}
if (!fields[fieldName]) {
if (allowResolversNotInSchema) {
return;
}
throw new SchemaError(
`${typeName}.${fieldName} defined in resolvers, but not in schema`,
);
}
const field = fields[fieldName];
const fieldResolve = resolvers[typeName][fieldName];
if (typeof fieldResolve === 'function') {
// for convenience. Allows shorter syntax in resolver definition file
setFieldProperties(field, { resolve: fieldResolve });
} else {
if (typeof fieldResolve !== 'object') {
throw new SchemaError(
`Resolver ${typeName}.${fieldName} must be object or function`,
);
}
setFieldProperties(field, fieldResolve);
}
});
});
checkForResolveTypeResolver(schema, requireResolversForResolveType);
}
function extendResolversFromInterfaces(schema: GraphQLSchema, resolvers: IResolvers) {
const typeNames = Object.keys({
...schema.getTypeMap(),
...resolvers
});
const extendedResolvers: IResolvers = {};
typeNames.forEach((typeName) => {
const typeResolvers = resolvers[typeName];
const type = schema.getType(typeName);
if (type instanceof GraphQLObjectType) {
const interfaceResolvers = type.getInterfaces().map((iFace) => resolvers[iFace.name]);
extendedResolvers[typeName] = Object.assign({}, ...interfaceResolvers, typeResolvers);
} else {
if (typeResolvers) {
extendedResolvers[typeName] = typeResolvers;
}
}
});
return extendedResolvers;
}
// If we have any union or interface types throw if no there is no resolveType or isTypeOf resolvers
function checkForResolveTypeResolver(schema: GraphQLSchema, requireResolversForResolveType?: boolean) {
Object.keys(schema.getTypeMap())
.map(typeName => schema.getType(typeName))
.forEach((type: GraphQLUnionType | GraphQLInterfaceType) => {
if (!(type instanceof GraphQLUnionType || type instanceof GraphQLInterfaceType)) {
return;
}
if (!type.resolveType) {
if (requireResolversForResolveType === false) {
return;
}
if (requireResolversForResolveType === true) {
throw new SchemaError(`Type "${type.name}" is missing a "resolveType" resolver`);
}
// tslint:disable-next-line:max-line-length
console.warn(`Type "${type.name}" is missing a "resolveType" resolver. Pass false into "resolverValidationOptions.requireResolversForResolveType" to disable this warning.`);
}
});
}
function setFieldProperties(
field: GraphQLField<any, any>,
propertiesObj: Object,
) {
Object.keys(propertiesObj).forEach(propertyName => {
field[propertyName] = propertiesObj[propertyName];
});
}
function assertResolveFunctionsPresent(
schema: GraphQLSchema,
resolverValidationOptions: IResolverValidationOptions = {},
) {
const {
requireResolversForArgs = false,
requireResolversForNonScalar = false,
requireResolversForAllFields = false,
} = resolverValidationOptions;
if (
requireResolversForAllFields &&
(requireResolversForArgs || requireResolversForNonScalar)
) {
throw new TypeError(
'requireResolversForAllFields takes precedence over the more specific assertions. ' +
'Please configure either requireResolversForAllFields or requireResolversForArgs / ' +
'requireResolversForNonScalar, but not a combination of them.',
);
}
forEachField(schema, (field, typeName, fieldName) => {
// requires a resolve function for *every* field.
if (requireResolversForAllFields) {
expectResolveFunction(field, typeName, fieldName);
}
// requires a resolve function on every field that has arguments
if (requireResolversForArgs && field.args.length > 0) {
expectResolveFunction(field, typeName, fieldName);
}
// requires a resolve function on every field that returns a non-scalar type
if (
requireResolversForNonScalar &&
!(getNamedType(field.type) instanceof GraphQLScalarType)
) {
expectResolveFunction(field, typeName, fieldName);
}
});
}
function expectResolveFunction(
field: GraphQLField<any, any>,
typeName: string,
fieldName: string,
) {
if (!field.resolve) {
console.warn(
// tslint:disable-next-line: max-line-length
`Resolve function missing for "${typeName}.${fieldName}". To disable this warning check https://github.com/apollostack/graphql-tools/issues/131`,
);
return;
}
if (typeof field.resolve !== 'function') {
throw new SchemaError(
`Resolver "${typeName}.${fieldName}" must be a function`,
);
}
}
function addErrorLoggingToSchema(schema: GraphQLSchema, logger: ILogger): void {
if (!logger) {
throw new Error('Must provide a logger');
}
if (typeof logger.log !== 'function') {
throw new Error('Logger.log must be a function');
}
forEachField(schema, (field, typeName, fieldName) => {
const errorHint = `${typeName}.${fieldName}`;
field.resolve = decorateWithLogger(field.resolve, logger, errorHint);
});
}
// XXX badly named function. this doesn't really wrap, it just chains resolvers...
function wrapResolver(
innerResolver: GraphQLFieldResolver<any, any> | undefined,
outerResolver: GraphQLFieldResolver<any, any>,
): GraphQLFieldResolver<any, any> {
return (obj, args, ctx, info) => {
return Promise.resolve(outerResolver(obj, args, ctx, info)).then(root => {
if (innerResolver) {
return innerResolver(root, args, ctx, info);
}
return defaultFieldResolver(root, args, ctx, info);
});
};
}
function chainResolvers(resolvers: GraphQLFieldResolver<any, any>[]) {
return (
root: any,
args: { [argName: string]: any },
ctx: any,
info: GraphQLResolveInfo,
) => {
return resolvers.reduce((prev, curResolver) => {
if (curResolver) {
return curResolver(prev, args, ctx, info);
}
return defaultFieldResolver(prev, args, ctx, info);
}, root);
};
}
/*
* fn: The function to decorate with the logger
* logger: an object instance of type Logger
* hint: an optional hint to add to the error's message
*/
function decorateWithLogger(
fn: GraphQLFieldResolver<any, any> | undefined,
logger: ILogger,
hint: string,
): GraphQLFieldResolver<any, any> {
if (typeof fn === 'undefined') {
fn = defaultFieldResolver;
}
const logError = (e: Error) => {
// TODO: clone the error properly
const newE = new Error();
newE.stack = e.stack;
/* istanbul ignore else: always get the hint from addErrorLoggingToSchema */
if (hint) {
newE['originalMessage'] = e.message;
newE['message'] = `Error in resolver ${hint}\n${e.message}`;
}
logger.log(newE);
};
return (root, args, ctx, info) => {
try {
const result = fn(root, args, ctx, info);
// If the resolve function returns a Promise log any Promise rejects.
if (
result &&
typeof result.then === 'function' &&
typeof result.catch === 'function'
) {
result.catch((reason: Error | string) => {
// make sure that it's an error we're logging.
const error = reason instanceof Error ? reason : new Error(reason);
logError(error);
// We don't want to leave an unhandled exception so pass on error.
return reason;
});
}
return result;
} catch (e) {
logError(e);
// we want to pass on the error, just in case.
throw e;
}
};
}
function addCatchUndefinedToSchema(schema: GraphQLSchema): void {
forEachField(schema, (field, typeName, fieldName) => {
const errorHint = `${typeName}.${fieldName}`;
field.resolve = decorateToCatchUndefined(field.resolve, errorHint);
});
}
function decorateToCatchUndefined(
fn: GraphQLFieldResolver<any, any>,
hint: string,
): GraphQLFieldResolver<any, any> {
if (typeof fn === 'undefined') {
fn = defaultFieldResolver;
}
return (root, args, ctx, info) => {
const result = fn(root, args, ctx, info);
if (typeof result === 'undefined') {
throw new Error(`Resolve function for "${hint}" returned undefined`);
}
return result;
};
}
// XXX this function only works for resolvers
// XXX very hacky way to remember if the function
// already ran for this request. This will only work
// if people don't actually cache the operation.
// if they do cache the operation, they will have to
// manually remove the __runAtMostOnce before every request.
function runAtMostOncePerRequest(
fn: GraphQLFieldResolver<any, any>,
): GraphQLFieldResolver<any, any> {
let value: any;
const randomNumber = Math.random();
return (root, args, ctx, info) => {
if (!info.operation['__runAtMostOnce']) {
info.operation['__runAtMostOnce'] = {};
}
if (!info.operation['__runAtMostOnce'][randomNumber]) {
info.operation['__runAtMostOnce'][randomNumber] = true;
value = fn(root, args, ctx, info);
}
return value;
};
}
function attachDirectiveResolvers(
schema: GraphQLSchema,
directiveResolvers: IDirectiveResolvers<any, any>,
) {
if (typeof directiveResolvers !== 'object') {
throw new Error(
`Expected directiveResolvers to be of type object, got ${typeof directiveResolvers}`,
);
}
if (Array.isArray(directiveResolvers)) {
throw new Error(
'Expected directiveResolvers to be of type object, got Array',
);
}
const schemaDirectives = Object.create(null);
Object.keys(directiveResolvers).forEach(directiveName => {
schemaDirectives[directiveName] = class extends SchemaDirectiveVisitor {
public visitFieldDefinition(field: GraphQLField<any, any>) {
const resolver = directiveResolvers[directiveName];
const originalResolver = field.resolve || defaultFieldResolver;
const directiveArgs = this.args;
field.resolve = (...args: any[]) => {
const [source, /* original args */, context, info] = args;
return resolver(
async () => originalResolver.apply(field, args),
source,
directiveArgs,
context,
info,
);
};
}
};
});
SchemaDirectiveVisitor.visitSchemaDirectives(
schema,
schemaDirectives,
);
}
export {
makeExecutableSchema,
SchemaError,
forEachField,
chainResolvers,
addErrorLoggingToSchema,
addResolveFunctionsToSchema,
addCatchUndefinedToSchema,
assertResolveFunctionsPresent,
buildSchemaFromTypeDefinitions,
addSchemaLevelResolveFunction,
attachConnectorsToContext,
concatenateTypeDefs,
attachDirectiveResolvers,
};