-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
typeComposer.js
558 lines (477 loc) · 15.9 KB
/
typeComposer.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
/* @flow */
import {
GraphQLObjectType,
GraphQLList,
GraphQLInputObjectType,
} from 'graphql';
import { resolveMaybeThunk } from './utils/misc';
import { isObject, isFunction, isString } from './utils/is';
import { unwrapFieldsType, wrapFieldsType } from './utils/typeAsFn';
import { deprecate } from './utils/debug';
import Resolver from './resolver';
import { toInputObjectType } from './toInputObjectType';
import InputTypeComposer from './inputTypeComposer';
import TypeMapper from './typeMapper';
import { typeByPath } from './typeByPath';
import type {
Thunk,
GraphQLFieldConfig,
GraphQLFieldConfigMap,
GraphQLOutputType,
GraphQLObjectTypeConfig,
GraphQLObjectTypeExtended,
GraphQLInterfaceType,
GetRecordIdFn,
RelationOpts,
RelationOptsWithResolver,
RelationThunkMap,
RelationArgsMapperFn,
GraphQLFieldConfigArgumentMap,
GraphQLArgumentConfig,
ProjectionType,
ProjectionMapType,
ResolverOpts,
TypeNameString,
TypeDefinitionString,
} from './definition';
export default class TypeComposer {
gqType: GraphQLObjectTypeExtended;
static create(
opts: TypeNameString | TypeDefinitionString | GraphQLObjectTypeConfig | GraphQLObjectType
) {
let TC;
if (isString(opts)) {
// $FlowFixMe
const typeName: string = opts;
const NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
if (NAME_RX.test(typeName)) {
TC = new TypeComposer(new GraphQLObjectType({
name: typeName,
fields: () => ({}),
}));
} else {
const type = TypeMapper.createType(typeName);
if (!(type instanceof GraphQLObjectType)) {
throw new Error('You should provide correct GraphQLObjectType type definition.');
}
TC = new TypeComposer(type);
}
} else if (opts instanceof GraphQLObjectType) {
TC = new TypeComposer(opts);
} else if (isObject(opts)) {
// $FlowFixMe
const type = new GraphQLObjectType({
...opts,
fields: () => ({}),
});
TC = new TypeComposer(type);
// $FlowFixMe
if (isObject(opts.fields)) {
// $FlowFixMe
TC.addFields(opts.fields);
}
} else {
throw new Error('You should provide GraphQLObjectTypeConfig or string with type name to TypeComposer.create(opts)');
}
return TC;
}
constructor(gqType: GraphQLObjectType) {
this.gqType = gqType;
}
/**
* Get fields from a GraphQL type
* WARNING: this method read an internal GraphQL instance variable.
*/
getFields(): GraphQLFieldConfigMap<*, *> {
const fields: Thunk<GraphQLFieldConfigMap<*, *>>
= this.gqType._typeConfig.fields;
// $FlowFixMe
const fieldMap:mixed = wrapFieldsType(resolveMaybeThunk(fields));
if (isObject(fieldMap)) {
// $FlowFixMe
return Object.assign({}, fieldMap);
}
return {};
}
getFieldNames(): string[] {
return Object.keys(this.getFields());
}
/**
* Completely replace all fields in GraphQL type
* WARNING: this method rewrite an internal GraphQL instance variable.
*/
setFields(fields: GraphQLFieldConfigMap<*, *>): void {
const prepearedFields = TypeMapper.convertOutputFieldConfigMap(
fields,
this.getTypeName()
);
// if field has a projection option, then add it to projection mapper
Object.keys(prepearedFields).forEach((name) => {
if (prepearedFields[name].projection) {
// $FlowFixMe
const projection: ProjectionType = prepearedFields[name].projection;
this.addProjectionMapper(name, projection);
}
});
// $FlowFixMe
this.gqType._typeConfig.fields = () => unwrapFieldsType(prepearedFields);
delete this.gqType._fields; // clear builded fields in type
}
hasField(fieldName: string): boolean {
const fields = this.getFields();
return !!fields[fieldName];
}
setField<TSource, TContext>(
fieldName: string,
fieldConfig: GraphQLFieldConfig<TSource, TContext>
) {
this.addFields({ [fieldName]: fieldConfig });
}
/**
* @deprecated 2.0.0
*/
addField(
fieldName: string,
fieldConfig: GraphQLFieldConfig<*, *>
) {
deprecate('Use TypeComposer.setField() or plural addFields({}) instead.');
this.addFields({ [fieldName]: fieldConfig });
}
/**
* Add new fields or replace existed in a GraphQL type
*/
addFields(newFields: GraphQLFieldConfigMap<*, *>): void {
this.setFields(Object.assign({}, this.getFields(), newFields));
}
/**
* Get fieldConfig by name
*/
getField(fieldName: string): ?GraphQLFieldConfig<*, *> {
const fields = this.getFields();
if (fields[fieldName]) {
return fields[fieldName];
}
return undefined;
}
removeField(fieldNameOrArray: string | Array<string>): void {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
const fields = this.getFields();
fieldNames.forEach(fieldName => delete fields[fieldName]);
this.setFields(Object.assign({}, fields)); // immutability
}
extendField<TSource, TContext>(
name: string,
parialFieldConfig: GraphQLFieldConfig<TSource, TContext>
): GraphQLFieldConfig<TSource, TContext> {
const fieldConfig = Object.assign({}, this.getField(name), parialFieldConfig);
this.setField(name, fieldConfig);
return fieldConfig;
}
addRelation(
fieldName: string,
relationFn: Thunk<RelationOpts<*, *>>
): TypeComposer {
if (!this.gqType._gqcRelations) {
this.gqType._gqcRelations = {};
}
this.gqType._gqcRelations[fieldName] = relationFn;
return this;
}
getRelations(): RelationThunkMap<*, *> {
if (!this.gqType._gqcRelations) {
this.gqType._gqcRelations = {};
}
return this.gqType._gqcRelations;
}
buildRelations(): void {
const relationFields = {};
const names = Object.keys(this.getRelations());
names.forEach((fieldName) => {
relationFields[fieldName] = this.buildRelation(fieldName);
});
}
buildRelation(fieldName: string): void {
if (!this.gqType._gqcRelations || !isFunction(this.gqType._gqcRelations[fieldName])) {
throw new Error(`Cannot call buildRelation() for type ${this.getTypeName()}. `
+ `Relation with name '${fieldName}' does not exist.`);
}
const relationFn: Thunk<RelationOpts<*, *>> = this.gqType._gqcRelations[fieldName];
// $FlowFixMe
const relationOpts: RelationOpts = relationFn();
if (relationOpts.resolver) {
if (!(relationOpts.resolver instanceof Resolver)) {
throw new Error('You should provide correct Resolver object for relation '
+ `${this.getTypeName()}.${fieldName}`);
}
if (relationOpts.type) {
throw new Error('You can not use `resolver` and `type` properties simultaneously for relation '
+ `${this.getTypeName()}.${fieldName}`);
}
if (relationOpts.resolve) {
throw new Error('You can not use `resolver` and `resolve` properties simultaneously for relation '
+ `${this.getTypeName()}.${fieldName}`);
}
this.addRelationWithResolver(fieldName, relationOpts.resolver, relationOpts);
} else if (relationOpts.type) {
this.setField(fieldName, {
...relationOpts,
_gqcIsRelation: true,
});
}
}
addRelationWithResolver<TSource, TContext>(
fieldName: string,
resolver: Resolver<TSource, TContext>,
opts: RelationOptsWithResolver<TSource, TContext>
): TypeComposer {
const resolverFieldConfig = resolver.getFieldConfig();
const argsConfig = Object.assign({}, resolverFieldConfig.args);
const argsProto = {};
const argsRuntime: ([string, RelationArgsMapperFn<TSource, TContext>])[] = [];
// remove args from config, if arg name provided in args
// if `argMapVal`
// is `undefined`, then keep arg field in config
// is `null`, then just remove arg field from config
// is `function`, then remove arg field and run it in resolve
// is any other value, then put it to args prototype for resolve
const optsArgs = opts.args || {};
Object.keys(optsArgs).forEach((argName) => {
const argMapVal = optsArgs[argName];
if (argMapVal !== undefined) {
delete argsConfig[argName];
if (isFunction(argMapVal)) {
// $FlowFixMe
argsRuntime.push([argName, argMapVal]);
} else if (argMapVal !== null) {
argsProto[argName] = argMapVal;
}
}
});
// if opts.catchErrors is undefined then set true, otherwise take it value
const { catchErrors = true } = opts;
const resolve = (source, args, context, info) => {
const newArgs = Object.assign({}, args, argsProto);
argsRuntime.forEach(([argName, argFn]) => {
newArgs[argName] = argFn(source, args, context, info);
});
const payload = resolverFieldConfig.resolve(source, newArgs, context, info);
return catchErrors
? Promise.resolve(payload).catch((e) => {
console.log( // eslint-disable-line
`GQC ERROR: relation for ${this.getTypeName()}.${fieldName} throws error:`
);
console.log(e); // eslint-disable-line
return null;
})
: payload;
};
this.setField(fieldName, {
type: resolverFieldConfig.type,
description: opts.description,
deprecationReason: opts.deprecationReason,
args: argsConfig,
resolve,
projection: opts.projection,
_gqcIsRelation: true,
});
return this;
}
/**
* Get fields from a GraphQL type
* WARNING: this method read an internal GraphQL instance variable.
*/
getInterfaces(): Array<GraphQLInterfaceType> {
const interfaces: Array<GraphQLInterfaceType> | Thunk<?Array<GraphQLInterfaceType>>
= this.gqType._typeConfig.interfaces;
if (typeof interfaces === 'function') {
return interfaces() || [];
}
return interfaces || [];
}
/**
* Completely replace all interfaces in GraphQL type
* WARNING: this method rewrite an internal GraphQL instance variable.
*/
setInterfaces(interfaces: Array<GraphQLInterfaceType>): void {
this.gqType._typeConfig.interfaces = interfaces;
delete this.gqType._interfaces; // if schema was builded, delete _interfaces
}
hasInterface(interfaceObj: GraphQLInterfaceType): boolean {
return this.getInterfaces().indexOf(interfaceObj) > -1;
}
addInterface(interfaceObj: GraphQLInterfaceType): void {
if (!this.hasInterface(interfaceObj)) {
this.setInterfaces([...this.getInterfaces(), interfaceObj]);
}
}
removeInterface(interfaceObj: GraphQLInterfaceType): void {
const interfaces = this.getInterfaces();
const idx = interfaces.indexOf(interfaceObj);
if (idx > -1) {
interfaces.splice(idx, 1);
this.setInterfaces(interfaces);
}
}
clone(newTypeName: string): TypeComposer {
if (!newTypeName) {
throw new Error('You should provide newTypeName:string for TypeComposer.clone()');
}
const fields = this.getFields();
const newFields = {};
Object.keys(fields).forEach((fieldName) => {
newFields[fieldName] = Object.assign({}, fields[fieldName]);
});
const cloned = new TypeComposer(
new GraphQLObjectType({
name: newTypeName,
fields: newFields,
})
);
cloned.gqType._gqcProjectionMapper = this.gqType._gqcProjectionMapper;
cloned.setDescription(this.getDescription());
try {
cloned.setRecordIdFn(this.getRecordIdFn());
} catch (e) {
// no problem, clone without resolveIdFn
}
this.getResolvers().forEach((resolver) => {
const newResolver = resolver.clone(cloned);
cloned.addResolver(newResolver);
});
return cloned;
}
/**
* Get fieldType by name
*/
getFieldType(fieldName: string): GraphQLOutputType | void {
const field = this.getField(fieldName);
if (field) {
return field.type;
}
return undefined;
}
getType(): GraphQLObjectType {
return this.gqType;
}
getTypePlural(): GraphQLObjectType {
return new GraphQLList(this.gqType);
}
getInputType(): GraphQLInputObjectType {
return this.getInputTypeComposer().getType();
}
hasInputTypeComposer(): boolean {
return !!this.gqType._gqcInputTypeComposer;
}
getInputTypeComposer(): InputTypeComposer {
if (!this.gqType._gqcInputTypeComposer) {
this.gqType._gqcInputTypeComposer = toInputObjectType(this);
}
return this.gqType._gqcInputTypeComposer;
}
getResolvers(): Map<string, Resolver<*, *>> {
if (!this.gqType._gqcResolvers) {
this.gqType._gqcResolvers = new Map();
}
return this.gqType._gqcResolvers;
}
hasResolver(name: string): boolean {
if (!this.gqType._gqcResolvers) {
return false;
}
return this.gqType._gqcResolvers.has(name);
}
getResolver(name: string): Resolver<*, *> | void {
if (this.hasResolver(name) && this.gqType._gqcResolvers) {
return this.gqType._gqcResolvers.get(name);
}
return undefined;
}
setResolver(name: string, resolver: Resolver<*, *>): void {
if (!this.gqType._gqcResolvers) {
this.gqType._gqcResolvers = new Map();
}
if (!(resolver instanceof Resolver)) {
throw new Error('setResolver() accept only Resolver instance');
}
this.gqType._gqcResolvers.set(name, resolver);
}
addResolver(resolver: Resolver<*, *> | ResolverOpts<*, *>): void {
if (!(resolver instanceof Resolver)) {
resolver = new Resolver(resolver); // eslint-disable-line no-param-reassign
}
if (!resolver.name) {
throw new Error('resolver should have non-empty name property');
}
this.setResolver(resolver.name, resolver);
}
removeResolver(resolverName: string): void {
if (resolverName) {
this.getResolvers().delete(resolverName);
}
}
getTypeName(): string {
return this.gqType.name;
}
setTypeName(name: string): void {
this.gqType.name = name;
}
getDescription(): string {
return this.gqType.description || '';
}
setDescription(description: string): void {
this.gqType.description = description;
}
setRecordIdFn(fn: GetRecordIdFn<*, *>): void {
this.gqType._gqcGetRecordIdFn = fn;
}
hasRecordIdFn(): boolean {
return !!this.gqType._gqcGetRecordIdFn;
}
getRecordIdFn(): GetRecordIdFn<*, *> {
if (!this.gqType._gqcGetRecordIdFn) {
throw new Error(`Type ${this.getTypeName()} does not have RecordIdFn`);
}
return this.gqType._gqcGetRecordIdFn;
}
/**
* Get function that returns record id, from provided object.
*/
getRecordId(source: ?mixed, args: ?mixed, context: ?mixed): string | number {
return this.getRecordIdFn()(source, args, context);
}
getFieldArgs(fieldName: string): ?GraphQLFieldConfigArgumentMap {
const field = this.getField(fieldName);
if (field) {
return field.args;
}
return null;
}
getFieldArg(fieldName: string, argName: string): ?GraphQLArgumentConfig {
const fieldArgs = this.getFieldArgs(fieldName) || {};
return fieldArgs[argName] ? fieldArgs[argName] : undefined;
}
/**
* @deprecated 2.0.0
*/
getByPath(path: string | Array<string>): mixed {
deprecate('Use TypeComposer.get() instead.');
return this.get(path);
}
get(path: string | Array<string>): mixed {
return typeByPath(this, path);
}
// Sometimes, when you create relations or some tricky fields,
// you should have a data from additional fields, that not in a query projection.
// E.g. for obtaining `friendList` you also should add `friendIds` to projection.
// or for `fullname` field you should request `firstname` and `lastname` from DB.
// this _gqcProjectionMapper used in `projection` module
addProjectionMapper(fieldName: string, sourceProjection: ProjectionType):void {
if (!this.gqType._gqcProjectionMapper) {
this.gqType._gqcProjectionMapper = {};
}
this.gqType._gqcProjectionMapper[fieldName] = sourceProjection;
}
getProjectionMapper(): ProjectionMapType {
return this.gqType._gqcProjectionMapper || {};
}
}