/
resolver.js
698 lines (624 loc) · 20.8 KB
/
resolver.js
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
/* @flow */
/* eslint-disable no-use-before-define, no-restricted-syntax */
import objectPath from 'object-path';
import util from 'util';
import {
GraphQLInputObjectType,
GraphQLNonNull,
GraphQLEnumType,
GraphQLObjectType,
isOutputType,
isInputType,
} from 'graphql';
// import { deprecate } from './utils/debug';
import TypeMapper from './typeMapper';
import TypeComposer from './typeComposer';
import deepmerge from './utils/deepmerge';
import { resolveInputConfigsAsThunk } from './utils/configAsThunk';
import { only, clearName } from './utils/misc';
import { isFunction, isString } from './utils/is';
import filterByDotPaths from './utils/filterByDotPaths';
import { getProjectionFromAST } from './projection';
import type {
GraphQLArgumentConfig,
GraphQLFieldConfigArgumentMap,
GraphQLOutputType,
GraphQLFieldConfig,
ResolverMWResolve,
ResolverMWResolveFn,
ResolveParams,
ResolverKinds,
ProjectionType,
ResolverFilterArgConfig,
ResolverSortArgConfig,
ResolverOpts,
ResolverWrapFn,
ResolverWrapArgsFn,
ResolverWrapTypeFn,
GraphQLInputType,
ComposeOutputType,
ComposeArgumentConfig,
ComposeFieldConfigArgumentMap,
} from './definition';
import InputTypeComposer from './inputTypeComposer';
import { typeByPath } from './typeByPath';
export type ResolveDebugOpts = {
showHidden?: boolean,
depth?: number,
colors?: boolean,
};
export default class Resolver<TSource, TContext> {
type: GraphQLOutputType;
args: GraphQLFieldConfigArgumentMap;
resolve: ResolverMWResolveFn<TSource, TContext>;
name: string;
displayName: ?string;
kind: ?ResolverKinds;
description: ?string;
parent: ?Resolver<TSource, TContext>;
constructor(opts: ResolverOpts<TSource, TContext>) {
if (!opts.name) {
throw new Error('For Resolver constructor the `opts.name` is required option.');
}
this.name = opts.name;
this.displayName = opts.displayName || null;
this.parent = opts.parent || null;
this.kind = opts.kind || null;
this.description = opts.description || '';
if (opts.type) {
this.setType(opts.type);
}
if (opts.args) {
this.args = TypeMapper.convertArgConfigMap(opts.args, this.name, 'Resolver');
} else {
this.args = {};
}
if (opts.resolve) {
this.resolve = opts.resolve;
}
}
hasArg(argName: string): boolean {
return !!this.args[argName];
}
getArg(argName: string): GraphQLArgumentConfig {
if (!this.hasArg(argName)) {
throw new Error(
`Cannot get arg '${argName}' for resolver ${this.name}. Argument does not exist.`
);
}
return this.args[argName];
}
getArgType(argName: string): GraphQLInputType {
const arg = this.getArg(argName);
return arg.type;
}
getArgTC(argName: string): InputTypeComposer {
const argType = this.getArgType(argName);
if (!(argType instanceof GraphQLInputObjectType)) {
throw new Error(
`Cannot get InputTypeComposer for arg '${argName}' in resolver ${this.getNestedName()}. ` +
`This argument should be InputObjectType, but it has type '${argType.constructor.name}'`
);
}
return new InputTypeComposer(argType);
}
getArgs(): GraphQLFieldConfigArgumentMap {
return this.args;
}
getArgNames(): string[] {
return Object.keys(this.args);
}
setArgs(args: ComposeFieldConfigArgumentMap): Resolver<TSource, TContext> {
this.args = TypeMapper.convertArgConfigMap(args, this.name, 'Resolver');
return this;
}
setArg(argName: string, argConfig: ComposeArgumentConfig): Resolver<TSource, TContext> {
this.args[argName] = TypeMapper.convertArgConfig(argConfig, argName, this.name, 'Resolver');
return this;
}
addArgs(newArgs: ComposeFieldConfigArgumentMap): Resolver<TSource, TContext> {
this.setArgs({ ...this.getArgs(), ...newArgs });
return this;
}
removeArg(argNameOrArray: string | Array<string>): Resolver<TSource, TContext> {
const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray];
argNames.forEach(argName => {
delete this.args[argName];
});
return this;
}
removeOtherArgs(argNameOrArray: string | Array<string>): Resolver<TSource, TContext> {
const keepArgNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray];
Object.keys(this.args).forEach(argName => {
if (keepArgNames.indexOf(argName) === -1) {
delete this.args[argName];
}
});
return this;
}
reorderArgs(names: string[]): Resolver<TSource, TContext> {
const orderedArgs = {};
names.forEach(name => {
if (this.args[name]) {
orderedArgs[name] = this.args[name];
delete this.args[name];
}
});
this.args = { ...orderedArgs, ...this.args };
return this;
}
cloneArg(argName: string, newTypeName: string): Resolver<TSource, TContext> {
if (!{}.hasOwnProperty.call(this.args, argName)) {
throw new Error(
`Can not clone arg ${argName} for resolver ${this.name}. Argument does not exist.`
);
}
let originalType = this.args[argName].type;
let isUnwrapped = false;
if (originalType instanceof GraphQLNonNull) {
originalType = originalType.ofType;
isUnwrapped = true;
}
if (!(originalType instanceof GraphQLInputObjectType)) {
throw new Error(
`Can not clone arg ${argName} for resolver ${this.name}.` +
'Argument should be GraphQLInputObjectType (complex input type).'
);
}
if (!newTypeName || newTypeName !== clearName(newTypeName)) {
throw new Error('You should provide new type name as second argument');
}
if (newTypeName === originalType.name) {
throw new Error('You should provide new type name. It is equal to current name.');
}
let clonedType = InputTypeComposer.create(originalType).clone(newTypeName).getType();
if (isUnwrapped) {
clonedType = new GraphQLNonNull(clonedType);
}
this.args[argName] = {
...this.args[argName],
type: clonedType,
};
return this;
}
isRequired(argName: string): boolean {
return this.getArgType(argName) instanceof GraphQLNonNull;
}
makeRequired(argNameOrArray: string | Array<string>): Resolver<TSource, TContext> {
const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray];
argNames.forEach(argName => {
if (this.args[argName]) {
const argType = this.args[argName].type;
if (!isInputType(argType)) {
throw new Error(
`Cannot make argument ${argName} required. It should be InputType: ${JSON.stringify(
argType
)}`
);
}
if (!(argType instanceof GraphQLNonNull)) {
this.args[argName].type = new GraphQLNonNull(argType);
}
}
});
return this;
}
makeOptional(argNameOrArray: string | Array<string>): Resolver<TSource, TContext> {
const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray];
argNames.forEach(argName => {
if (argNames.indexOf(argName) > -1) {
const argType = this.args[argName].type;
if (argType instanceof GraphQLNonNull) {
this.args[argName].type = argType.ofType;
}
}
});
return this;
}
/*
* This method should be overriden via constructor
*/
/* eslint-disable */
resolve(
resolveParams: ResolveParams<TSource, TContext> | $Shape<ResolveParams<TSource, TContext>>
): Promise<any> {
return Promise.resolve();
}
/* eslint-enable */
getResolve(): ResolverMWResolveFn<TSource, TContext> {
return this.resolve;
}
setResolve(resolve: ResolverMWResolveFn<TSource, TContext>): Resolver<TSource, TContext> {
this.resolve = resolve;
return this;
}
getType(): GraphQLOutputType {
return this.type;
}
getTypeComposer(): ?TypeComposer {
if (this.type instanceof GraphQLObjectType) {
return new TypeComposer(this.type);
}
return null;
}
setType(gqType: ComposeOutputType): Resolver<TSource, TContext> {
const fc = TypeMapper.convertOutputFieldConfig(gqType, 'setType', 'Resolver');
if (!fc || !isOutputType(fc.type)) {
throw new Error('You should provide correct OutputType for Resolver.type.');
}
this.type = fc.type;
return this;
}
getFieldConfig(
opts: {
projection?: ProjectionType,
} = {}
): GraphQLFieldConfig<TSource, TContext> {
const resolve = this.getResolve();
return {
type: this.getType(),
args: resolveInputConfigsAsThunk(this.getArgs()),
description: this.description,
resolve: (source, args, context, info) => {
let projection = getProjectionFromAST(info);
if (opts.projection) {
projection = ((deepmerge(projection, opts.projection): any): ProjectionType);
}
return resolve({ source, args, context, info, projection });
},
};
}
getKind(): ?ResolverKinds {
return this.kind;
}
setKind(kind: string): Resolver<TSource, TContext> {
if (kind !== 'query' && kind !== 'mutation' && kind !== 'subscription') {
throw new Error(
`You provide incorrect value '${kind}' for Resolver.setKind method. ` +
'Valid values are: query | mutation | subscription'
);
}
this.kind = kind;
return this;
}
getDescription(): ?string {
return this.description;
}
setDescription(description: string): Resolver<TSource, TContext> {
this.description = description;
return this;
}
get(path: string | Array<string>): any {
// $FlowFixMe
return typeByPath(this, path);
}
clone(opts: ResolverOpts<TSource, TContext> = {}): Resolver<TSource, TContext> {
const oldOpts = {};
for (const key in this) {
if ({}.hasOwnProperty.call(this, key)) {
// $FlowFixMe
oldOpts[key] = this[key];
}
}
oldOpts.displayName = undefined;
oldOpts.args = { ...this.args };
return new Resolver({ ...oldOpts, ...opts });
}
wrap(
cb: ?ResolverWrapFn<TSource, TContext>,
newResolverOpts: ?ResolverOpts<TSource, TContext> = {}
): Resolver<TSource, TContext> {
const prevResolver: Resolver<TSource, TContext> = this;
const newResolver = this.clone({
name: 'wrap',
parent: prevResolver,
...newResolverOpts,
});
if (isFunction(cb)) {
cb(newResolver, prevResolver);
}
return newResolver;
}
wrapResolve(
cb: ResolverMWResolve<TSource, TContext>,
wrapperName: string = 'wrapResolve'
): Resolver<TSource, TContext> {
return this.wrap(
(newResolver, prevResolver) => {
const newResolve = cb(prevResolver.getResolve());
newResolver.setResolve(newResolve);
return newResolver;
},
{ name: wrapperName }
);
}
wrapArgs(cb: ResolverWrapArgsFn, wrapperName: string = 'wrapArgs'): Resolver<TSource, TContext> {
return this.wrap(
(newResolver, prevResolver) => {
// clone prevArgs, to avoid changing args in callback
const prevArgs = { ...prevResolver.getArgs() };
const newArgs = cb(prevArgs);
newResolver.setArgs(newArgs);
return newResolver;
},
{ name: wrapperName }
);
}
wrapCloneArg(argName: string, newTypeName: string): Resolver<TSource, TContext> {
return this.wrap(
newResolver => {
newResolver.cloneArg(argName, newTypeName);
return newResolver;
},
{ name: 'cloneFilterArg' }
);
}
wrapType(cb: ResolverWrapTypeFn, wrapperName: string = 'wrapType'): Resolver<TSource, TContext> {
return this.wrap(
(newResolver, prevResolver) => {
const prevType = prevResolver.getType();
const newType = cb(prevType);
newResolver.setType(newType);
return newResolver;
},
{ name: wrapperName }
);
}
addFilterArg(opts: ResolverFilterArgConfig<TSource, TContext>): Resolver<TSource, TContext> {
if (!opts.name) {
throw new Error('For Resolver.addFilterArg the arg name `opts.name` is required.');
}
if (!opts.type) {
throw new Error('For Resolver.addFilterArg the arg type `opts.type` is required.');
}
const resolver = this.wrap(null, { name: 'addFilterArg' });
// get filterTC or create new one argument
const filter = resolver.hasArg('filter') ? resolver.getArg('filter') : undefined;
let filterITC;
if (filter && filter.type instanceof GraphQLInputObjectType) {
filterITC = new InputTypeComposer(filter.type);
} else {
if (!opts.filterTypeNameFallback || !isString(opts.filterTypeNameFallback)) {
throw new Error(
'For Resolver.addFilterArg needs to provide `opts.filterTypeNameFallback: string`. ' +
'This string will be used as unique name for `filter` type of input argument. ' +
'Eg. FilterXXXXXInput'
);
}
filterITC = InputTypeComposer.create(opts.filterTypeNameFallback);
}
let defaultValue;
if (filter && filter.defaultValue) {
defaultValue = filter.defaultValue;
}
if (opts.defaultValue) {
if (!defaultValue) {
defaultValue = {};
}
// $FlowFixMe
defaultValue[opts.name] = opts.defaultValue;
}
resolver.setArg('filter', {
type: filterITC.getType(),
description: (filter && filter.description) || undefined,
defaultValue,
});
filterITC.setField(opts.name, {
...only(opts, ['name', 'type', 'defaultValue', 'description']),
});
const resolveNext = resolver.getResolve();
if (isFunction(opts.query)) {
resolver.setResolve(resolveParams => {
const value = objectPath.get(resolveParams, ['args', 'filter', opts.name]);
if (value !== null && value !== undefined) {
if (!resolveParams.rawQuery) {
resolveParams.rawQuery = {}; // eslint-disable-line
}
opts.query(resolveParams.rawQuery, value, resolveParams);
}
return resolveNext(resolveParams);
});
}
return resolver;
}
addSortArg(opts: ResolverSortArgConfig<TSource, TContext>): Resolver<TSource, TContext> {
if (!opts.name) {
throw new Error('For Resolver.addSortArg the `opts.name` is required.');
}
if (!opts.value) {
throw new Error('For Resolver.addSortArg the `opts.value` is required.');
}
const resolver = this.wrap(null, { name: 'addSortArg' });
// get sortEnumType or create new one
let sortEnumType;
if (resolver.hasArg('sort')) {
const sort = resolver.getArg('sort');
if (sort.type instanceof GraphQLEnumType) {
sortEnumType = sort.type;
} else {
throw new Error(
'Resolver should have `sort` arg with type GraphQLEnumType. ' +
`But got: ${util.inspect(sort.type, { depth: 2 })} `
);
}
} else {
if (!opts.sortTypeNameFallback || !isString(opts.sortTypeNameFallback)) {
throw new Error(
'For Resolver.addSortArg needs to provide `opts.sortTypeNameFallback: string`. ' +
'This string will be used as unique name for `sort` type of input argument. ' +
'Eg. SortXXXXXEnum'
);
}
sortEnumType = new GraphQLEnumType({
name: opts.sortTypeNameFallback,
values: {
[opts.name]: {},
},
});
resolver.setArg('sort', { type: sortEnumType });
}
// extend sortEnumType with new sorting value
const existedIdx = sortEnumType._values.findIndex(o => o.name === opts.name);
if (existedIdx >= 0) {
sortEnumType._values.splice(existedIdx, 1);
}
delete sortEnumType._nameLookup;
delete sortEnumType._valueLookup;
sortEnumType._values.push({
name: opts.name,
description: opts.description,
isDeprecated: Boolean(opts.deprecationReason),
deprecationReason: opts.deprecationReason,
value: isFunction(opts.value) ? opts.name : opts.value,
});
// If sort value is evaluable (function), then wrap resolve method
const resolveNext = resolver.getResolve();
if (isFunction(opts.value)) {
resolver.setResolve(resolveParams => {
const value = objectPath.get(resolveParams, ['args', 'sort']);
if (value === opts.name) {
// $FlowFixMe
const newSortValue = opts.value(resolveParams);
resolveParams.args.sort = newSortValue; // eslint-disable-line
}
return resolveNext(resolveParams);
});
}
return resolver;
}
getNestedName() {
const name = this.displayName || this.name;
if (this.parent) {
return `${name}(${this.parent.getNestedName()})`;
}
return name;
}
toStringOld() {
function extendedInfo(resolver, spaces = '') {
return [
'Resolver(',
` name: ${resolver.name},`,
` displayName: ${resolver.displayName || ''},`,
` type: ${util.inspect(resolver.type, { depth: 2 })},`,
` args: ${util.inspect(resolver.args, { depth: 3 }).replace('\n', `\n ${spaces}`)},`,
` resolve: ${resolver.resolve
? resolver.resolve.toString().replace('\n', `\n ${spaces}`)
: 'undefined'},`,
` parent: ${resolver.parent ? extendedInfo(resolver.parent, ` ${spaces}`) : ''}`,
')',
]
.filter(s => !!s)
.join(`\n ${spaces}`);
}
return extendedInfo(this);
}
toString(colors: boolean = true) {
return util.inspect(this.toDebugStructure(false), { depth: 20, colors }).replace(/\\n/g, '\n');
}
setDisplayName(name: string): this {
this.displayName = name;
return this;
}
toDebugStructure(colors: boolean = true): Object {
const info: any = {
name: this.name,
displayName: this.displayName,
type: util.inspect(this.type, { depth: 2, colors }),
args: this.args,
resolve: this.resolve ? this.resolve.toString() : this.resolve,
};
if (this.parent) {
info.resolve = [info.resolve, { 'Parent resolver': this.parent.toDebugStructure(colors) }];
}
return info;
}
debugExecTime(): Resolver<TSource, TContext> {
/* eslint-disable no-console */
return this.wrapResolve(
next => async rp => {
const name = `Execution time for ${this.getNestedName()}`;
console.time(name);
const res = await next(rp);
console.timeEnd(name);
return res;
},
'debugExecTime'
);
/* eslint-enable no-console */
}
debugParams(
filterPaths: ?(string | string[]),
opts?: ResolveDebugOpts = { colors: true, depth: 5 }
): Resolver<TSource, TContext> {
/* eslint-disable no-console */
return this.wrapResolve(
next => rp => {
console.log(`ResolveParams for ${this.getNestedName()}:`);
const data = filterByDotPaths(rp, filterPaths, {
// is hidden (use debugParams(["info"])) or debug({ params: ["info"]})
// `is hidden (use debugParams(["context.*"])) or debug({ params: ["context.*"]})`,
hideFields: rp && rp.context && rp.context.res && rp.context.params && rp.context.headers
? {
// looks like context is express request, colapse it
info: '[[hidden]]',
context: '[[hidden]]',
}
: {
info: '[[hidden]]',
'context.*': '[[hidden]]',
},
hideFieldsNote:
'Some data was [[hidden]] to display this fields use debugParams("%fieldNames%")',
});
console.dir(data, opts);
return next(rp);
},
'debugParams'
);
/* eslint-enable no-console */
}
debugPayload(
filterPaths: ?(string | string[]),
opts?: ResolveDebugOpts = { colors: true, depth: 5 }
): Resolver<TSource, TContext> {
/* eslint-disable no-console */
return this.wrapResolve(
next => async rp => {
try {
const res = await next(rp);
console.log(`Resolved Payload for ${this.getNestedName()}:`);
if (Array.isArray(res) && res.length > 3 && !filterPaths) {
console.dir(
[
filterPaths ? filterByDotPaths(res[0], filterPaths) : res[0],
`[debug note]: Other ${res.length - 1} records was [[hidden]]. ` +
'Use debugPayload("0 1 2 3 4") or debug({ payload: "0 1 2 3 4" }) for display this records',
],
opts
);
} else {
console.dir(filterPaths ? filterByDotPaths(res, filterPaths) : res, opts);
}
return res;
} catch (e) {
console.log(`Rejected Payload for ${this.getNestedName()}:`);
console.log(e);
throw e;
}
},
'debugPayload'
);
/* eslint-enable no-console */
}
debug(
filterDotPaths?: {
params?: ?(string | string[]),
payload?: ?(string | string[]),
},
opts?: ResolveDebugOpts = { colors: true, depth: 2 }
): Resolver<TSource, TContext> {
return this.debugExecTime()
.debugParams(filterDotPaths ? filterDotPaths.params : null, opts)
.debugPayload(filterDotPaths ? filterDotPaths.payload : null, opts);
}
}