forked from prisma/prisma1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.ts
509 lines (456 loc) · 14.2 KB
/
generator.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
import {
GraphQLScalarType,
GraphQLType,
GraphQLInterfaceType,
GraphQLSchema,
GraphQLFieldConfigMap,
GraphQLInputObjectType,
GraphQLFieldConfig,
GraphQLObjectType,
GraphQLInputFieldConfigMap,
GraphQLInputFieldConfig,
GraphQLFieldConfigArgumentMap,
GraphQLEnumType,
GraphQLEnumValueConfig,
GraphQLEnumValueConfigMap,
} from 'graphql/type'
import { IGQLType, IGQLField } from '../datamodel/model'
import { GraphQLList, GraphQLNonNull } from 'graphql';
// tslint:disable:max-classes-per-file
/**
* Type cache for object types.
*/
export class TypeRegistry {
[typeName: string]: GraphQLType
}
/**
* Base class of all generators,
* has a reference to the set of generators we need
* and a type registry.
*/
export abstract class Generator<In, Args, Out> {
protected knownTypes: TypeRegistry
protected generators: IGenerators
constructor(knownTypes: TypeRegistry, generators: IGenerators) {
this.knownTypes = knownTypes
this.generators = generators
}
/**
* Generates the thing this generator is generating.
* @param model
* @param args
*/
public abstract generate(model: In, args: Args): Out
}
/**
* Base class for all generators that create types.
* This class implements caching via the given TypeRegistry.
*/
export abstract class TypeGenerator<In, Args, Type extends GraphQLType> extends Generator<In, Args, Type> {
public abstract getTypeName(input: In, args: Args)
public generate(input: In, args: Args): Type {
const name = this.getTypeName(input, args)
if (this.knownTypes.hasOwnProperty(name)) {
// Force cast should be safe because of the name lookup.
return this.knownTypes[name] as Type
} else {
const type = this.generateInternal(input, args)
this.knownTypes[name] = type
return type
}
}
protected abstract generateInternal(input: In, args?: Args): Type
}
/**
* Base class for all generators which map
* a type from the datamodel to some object type.
*
* This class adds provides methods that assemble
* a GraphQLObject type, for code re-use.
*
* Ideally a deriving class would override the
* generateScalarFieldType or generateRelationFieldType methods.
*/
export abstract class TypeFromModelGenerator<
Args, Type extends GraphQLType,
FieldConfig extends GraphQLFieldConfig<any, any> | GraphQLEnumValueConfig | GraphQLInputFieldConfig,
FieldConfigMap extends GraphQLFieldConfigMap<any, any> | GraphQLEnumValueConfigMap | GraphQLInputFieldConfigMap
> extends TypeGenerator<IGQLType, Args, Type> {
public static reservedFields = ['id', 'createdAt', 'updatedAt']
/**
* Checks if the given list of fields has
* a unique field.
* @param fields
*/
public static hasUniqueField(fields: IGQLField[]) {
return fields.filter(field => field.isUnique).length > 0
}
/**
* Checks if the given list of fields has
* other fields than the fields given in the second
* parameter.
* @param fields
* @param fieldNames
*/
public static hasFieldsExcept(fields: IGQLField[], ...fieldNames: string[]) {
return fields.filter(field => !fieldNames.includes(field.name)).length > 0
}
/**
* Indicates if the resulting type would be empty.
* @param model
* @param args
*/
public wouldBeEmpty(model: IGQLType, args: Args): boolean {
return false
}
/**
* Generates all fields of this type.
* @param model
* @param args
*/
protected generateFields(model: IGQLType, args: Args): FieldConfigMap {
const fields = {} as FieldConfigMap
for (const field of model.fields) {
const fieldSchema: FieldConfig | null = this.generators.scalarTypeGenerator.isScalarField(
field,
)
? this.generateScalarField(model, args, field)
: this.generateRelationField(model, args, field)
if (fieldSchema !== null) {
fields[field.name] = fieldSchema
}
}
return fields
}
/**
* Responsible to instantiate the correct GraphQL type
* for building the ast.
* @param name
* @param fields
*/
protected abstract instantiateObjectType(
name: string,
fields: () => FieldConfigMap,
)
/**
* Calls generateFields and wraps the result into a function.
* Then calls instantiateObjectType to create the actual AST node.
* @param model
* @param args
*/
protected generateInternal(model: IGQLType, args: Args): Type {
const fieldFunction = () => this.generateFields(model, args)
return this.instantiateObjectType(
this.getTypeName(model, args),
fieldFunction,
)
}
protected generateScalarField(
model: IGQLType,
args: Args,
field: IGQLField,
): FieldConfig | null {
const type = this.generateScalarFieldType(model, args, field)
if (type === null) {
return null
} else {
// We need a force-cast with any here, since we would need a type constraint for a type that depends on
// FieldConfig, which is something that TS cannot do.
return ({ type } as any) as FieldConfig
}
}
protected generateRelationField(
model: IGQLType,
args: Args,
field: IGQLField,
): FieldConfig | null {
const type = this.generateRelationFieldType(model, args, field)
if (type === null) {
return null
} else {
// We need a force-cast with any here, since we would need a type constraint for a type that depends on
// FieldConfig, which is something that TS cannot do.
return ({ type } as any) as FieldConfig
}
}
protected generateScalarFieldType(model: IGQLType, args: Args, field: IGQLField): GraphQLType | null {
return this.generators.scalarTypeGenerator.mapToScalarFieldType(field)
}
protected generateRelationFieldType(model: IGQLType, args: Args, field: IGQLField): GraphQLType | null {
throw new Error("Method not implemented.");
}
}
/**
* Base class for all generators that generate GraphQLEnums.
*/
export abstract class ModelEnumTypeGeneratorBase extends TypeFromModelGenerator<
{},
GraphQLEnumType,
GraphQLEnumValueConfig,
GraphQLEnumValueConfigMap
> {
protected instantiateObjectType(
name: string,
values: () => GraphQLEnumValueConfigMap,
) {
return new GraphQLEnumType({
name,
values: values()
})
}
}
/**
* Base class for all generators that generate GraphQLObjectTypes.
*/
export abstract class ModelObjectTypeGeneratorBase<
Args
> extends
TypeFromModelGenerator<
Args,
GraphQLObjectType,
GraphQLFieldConfig<any, any>,
GraphQLFieldConfigMap<any, any>
> {
protected instantiateObjectType(name: string, fields: () => GraphQLFieldConfigMap<any, any>) {
return new GraphQLObjectType({
name,
fields,
})
}
}
export abstract class ModelObjectTypeGenerator extends ModelObjectTypeGeneratorBase<{}> { }
/**
* Base class for all generators that generate GraphQLInputObjectTypes.
*/
export abstract class ModelInputObjectTypeGeneratorBase<
Args
> extends TypeFromModelGenerator<
Args,
GraphQLInputObjectType,
GraphQLInputFieldConfig,
GraphQLInputFieldConfigMap
> {
protected instantiateObjectType(
name: string,
fields: () => GraphQLInputFieldConfigMap,
) {
return new GraphQLInputObjectType({
name,
fields,
})
}
}
export abstract class ModelInputObjectTypeGenerator extends ModelInputObjectTypeGeneratorBase<{}> { }
/**
* Special base class for the scalar field generator.
*/
export abstract class ScalarTypeGeneratorBase extends TypeGenerator<
string | IGQLType,
{},
GraphQLScalarType
> {
abstract isScalarField(field: IGQLField): boolean
/**
* Maps a field to the scalar field type for output objects.
* @param field
*/
abstract mapToScalarFieldType(field: IGQLField): GraphQLType
/**
* Maps a field to the scalar field type for input objects.
* @param field
*/
abstract mapToScalarFieldTypeForInput(field: IGQLField): GraphQLType
/**
* Maps a field to the scalar field type, forces the field to be not nullable.
* @param field
*/
abstract mapToScalarFieldTypeForceRequired(
field: IGQLField,
): GraphQLType
/**
* Maps a field to the scalar field type, forces the field to be nullable.
* @param field
*/
abstract mapToScalarFieldTypeForceOptional(
field: IGQLField,
): GraphQLType
/**
* Transforms a given GraphQLScalarType into a list of the given type, according
* to the OpenCRUD spec.
* @param field
*/
abstract wrapList<T extends GraphQLType>(field: T): GraphQLList<GraphQLNonNull<T>>
abstract requiredIf<T extends GraphQLType>(condition: boolean, field: T): T | GraphQLNonNull<T>
abstract wraphWithModifiers<T extends GraphQLType>(field: IGQLField, type: T): T | GraphQLList<GraphQLNonNull<T>> | GraphQLNonNull<T>
}
/**
* Abstract base class for all generators that generate scalar input fields.
*/
export abstract class ScalarInputGenerator extends TypeGenerator<
IGQLType,
IGQLField,
GraphQLObjectType
> { }
/**
* Base class for generators that generate argument lists.
*/
export abstract class ArgumentsGenerator extends Generator<
IGQLType,
{},
GraphQLFieldConfigArgumentMap
> {
public wouldBeEmpty(model: IGQLType, args: {}): boolean {
return false
}
}
/**
* Arguments passed to generators that need to take a related field into account.
*/
export class RelatedGeneratorArgs {
relatedField: IGQLField
relatedType: IGQLType
relationName: string | null
}
/**
* Base class for generators that generate GraphQLObject types which take a related field into account.
*/
export abstract class RelatedModelInputObjectTypeGenerator extends ModelInputObjectTypeGeneratorBase<
RelatedGeneratorArgs
> { }
/**
* Base class for generators that generate a GraphQLObjectType without taking any input.
*/
export abstract class AuxillaryObjectTypeGenerator extends TypeGenerator<
null,
{},
GraphQLObjectType
> { }
/**
* Base class for generators that generate a GraphQLInterfaceType without taking any input.
*/
export abstract class AuxillaryInterfaceGenerator extends TypeGenerator<
null,
{},
GraphQLInterfaceType
> { }
/**
* Base class for generators that generate a GraphQLInputObjectType without taking any input.
*/
export abstract class AuxillaryInputObjectTypeGenerator extends TypeGenerator<
null,
{},
GraphQLInputObjectType
> { }
/**
* Base class for generators that generate a GraphQLEnumType without taking any input.
*/
export abstract class AuxillaryEnumGenerator extends TypeGenerator<
null,
{},
GraphQLEnumType
> { }
/**
* Base class for generators that generate a query, mutation or subscription object from
* a list of datamodel types.
*/
export abstract class RootGenerator extends TypeGenerator<
IGQLType[],
{},
GraphQLObjectType
> { }
/**
* Base class for generators that generate a schema from a list of datamodel types.
*/
export abstract class SchemaGeneratorBase extends Generator<IGQLType[], {}, GraphQLSchema> { }
/**
* Base class specifying a list of generators to implement.
*/
export interface IGenerators {
// Create
modelCreateInput: ModelInputObjectTypeGenerator
modelCreateOneInput: ModelInputObjectTypeGenerator
modelCreateManyInput: ModelInputObjectTypeGenerator
modelCreateWithoutRelatedInput: RelatedModelInputObjectTypeGenerator
modelCreateOneWithoutRelatedInput: RelatedModelInputObjectTypeGenerator
modelCreateManyWithoutRelatedInput: RelatedModelInputObjectTypeGenerator
scalarListCreateInput: ScalarInputGenerator
// Update
modelUpdateInput: ModelInputObjectTypeGenerator
modelUpdateDataInput: ModelInputObjectTypeGenerator
modelUpdateOneInput: ModelInputObjectTypeGenerator
modelUpdateOneRequiredInput: ModelInputObjectTypeGenerator
modelUpdateManyInput: ModelInputObjectTypeGenerator
modelUpdateWithoutRelatedDataInput: RelatedModelInputObjectTypeGenerator
modelUpdateOneWithoutRelatedInput: RelatedModelInputObjectTypeGenerator
modelUpdateOneRequiredWithoutRelatedInput: RelatedModelInputObjectTypeGenerator
modelUpdateManyWithoutRelatedInput: RelatedModelInputObjectTypeGenerator
scalarListUpdateInput: ScalarInputGenerator
modelUpdateWithWhereUniqueWithoutRelatedInput: RelatedModelInputObjectTypeGenerator
modelUpdateWithWhereUniqueNestedInput: ModelInputObjectTypeGenerator
// Upsert
modelUpsertNestedInput: ModelInputObjectTypeGenerator
modelUpsertWithWhereUniqueWithoutRelatedInput: RelatedModelInputObjectTypeGenerator
modelUpsertWithoutRelatedInput: RelatedModelInputObjectTypeGenerator
modelUpsertWithWhereUniqueNestedInput: ModelInputObjectTypeGenerator
// Deleting uses ModelWhereInput
// Querying
modelWhereUniqueInput: ModelInputObjectTypeGenerator
modelWhereInput: ModelInputObjectTypeGenerator
modelOrderByInput: ModelEnumTypeGeneratorBase
modelConnection: ModelObjectTypeGenerator
modelEdge: ModelObjectTypeGenerator
aggregateModel: ModelObjectTypeGenerator
pageInfo: AuxillaryObjectTypeGenerator
model: ModelObjectTypeGenerator
oneQueryArguments: ArgumentsGenerator
manyQueryArguments: ArgumentsGenerator
uniqueQueryArguments: ArgumentsGenerator
node: AuxillaryInterfaceGenerator
// Auxillary Types
batchPayload: AuxillaryObjectTypeGenerator
// Subscription
modelSubscriptionPayload: ModelObjectTypeGenerator
modelSubscriptionWhereInput: ModelInputObjectTypeGenerator
mutationType: AuxillaryEnumGenerator
modelPreviousValues: ModelObjectTypeGenerator
// Root
query: RootGenerator
mutation: RootGenerator
subscription: RootGenerator
schema: SchemaGeneratorBase
// Scalar
modelEnumTypeGenerator: ModelEnumTypeGeneratorBase
scalarTypeGenerator: ScalarTypeGeneratorBase
}
/**
* Utility class that merges field configration.
*/
export class FieldConfigUtils {
/**
* Merges all given field config maps.
* @param fieldMaps The field config maps to merge.
*/
public static merge<
T extends GraphQLFieldConfigMap<any, any> |
GraphQLInputFieldConfigMap
>
(...fieldMaps: T[]): T {
const newMap = {} as T
for (const fieldMap of fieldMaps) {
if (fieldMap === null) {
continue
}
Object.keys(fieldMap).forEach((name: string) => {
const field = fieldMap[name]
if (name in newMap) {
console.dir(fieldMaps)
throw new Error(
'Field configuration to merge has duplicate field names.',
)
}
newMap[name] = field
})
}
return newMap
}
}