This repository has been archived by the owner on Jan 14, 2021. It is now read-only.
/
query.ts
1372 lines (1245 loc) · 42.5 KB
/
query.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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import chalk from 'chalk'
import 'flat-map-polyfill'
import indent from 'indent-string'
import { /*dmmf, */ DMMFClass } from './dmmf'
import { DMMF } from './dmmf-types'
import {
ArgError,
AtLeastOneError,
AtMostOneError,
FieldError,
InvalidArgError,
InvalidFieldError,
} from './error-types'
import {
getGraphQLType,
getInputTypeName,
getOutputTypeName,
getSuggestion,
inputTypeToJson,
stringifyGraphQLType,
stringifyInputType,
unionBy,
wrapWithList,
} from './utils/common'
import { deepExtend } from './utils/deep-extend'
import { deepGet } from './utils/deep-set'
import { filterObject } from './utils/filterObject'
import { omit } from './utils/omit'
import { MissingItem, printJsonWithErrors } from './utils/printJsonErrors'
import { printStack } from './utils/printStack'
import stringifyObject from './utils/stringifyObject'
import { visit } from './visit'
const tab = 2
export class Document {
constructor(public readonly type: 'query' | 'mutation', public readonly children: Field[]) {
this.type = type
this.children = children
}
public toString() {
return `${this.type} {
${indent(this.children.map(String).join('\n'), tab)}
}`
}
public validate(select: any, isTopLevelQuery: boolean = false, originalMethod?: string) {
const invalidChildren = this.children.filter(child => child.hasInvalidChild || child.hasInvalidArg)
if (invalidChildren.length === 0) {
return
}
const fieldErrors: FieldError[] = []
const argErrors: ArgError[] = []
const prefix = select && select.select ? 'select' : select.include ? 'include' : undefined
for (const child of invalidChildren) {
const errors = child.collectErrors(prefix)
fieldErrors.push(...errors.fieldErrors.map(e => ({ ...e, path: isTopLevelQuery ? e.path : e.path.slice(1) })))
argErrors.push(...errors.argErrors.map(e => ({ ...e, path: isTopLevelQuery ? e.path : e.path.slice(1) })))
}
const topLevelQueryName = this.children[0].name
const queryName = isTopLevelQuery ? this.type : topLevelQueryName
const keyPaths: string[] = []
const valuePaths: string[] = []
const missingItems: MissingItem[] = []
for (const fieldError of fieldErrors) {
const path = this.normalizePath(fieldError.path, select).join('.')
if (fieldError.error.type === 'invalidFieldName') {
keyPaths.push(path)
const fieldType = fieldError.error.outputType
const { isInclude } = fieldError.error
fieldType.fields
.filter(field => (isInclude ? field.outputType.kind === 'object' : true))
.forEach(field => {
const splittedPath = path.split('.')
missingItems.push({
path: `${splittedPath.slice(0, splittedPath.length - 1).join('.')}.${field.name}`,
type: 'true',
isRequired: false,
})
})
} else if (fieldError.error.type === 'includeAndSelect') {
keyPaths.push('select')
keyPaths.push('include')
} else {
valuePaths.push(path)
}
if (
fieldError.error.type === 'emptySelect' ||
fieldError.error.type === 'noTrueSelect' ||
fieldError.error.type === 'emptyInclude'
) {
const selectPathArray = this.normalizePath(fieldError.path, select)
const selectPath = selectPathArray.slice(0, selectPathArray.length - 1).join('.')
const fieldType = fieldError.error.field.outputType.type as DMMF.OutputType
fieldType.fields
.filter(field => (fieldError.error.type === 'emptyInclude' ? field.outputType.kind === 'object' : true))
.forEach(field => {
missingItems.push({
path: `${selectPath}.${field.name}`,
type: 'true',
isRequired: false,
})
})
}
}
// an arg error can either be an invalid key or invalid value
for (const argError of argErrors) {
const path = this.normalizePath(argError.path, select).join('.')
if (argError.error.type === 'invalidName') {
keyPaths.push(path)
} else if (argError.error.type !== 'missingArg' && argError.error.type !== 'atLeastOne') {
valuePaths.push(path)
} else if (argError.error.type === 'missingArg') {
const type =
argError.error.missingType.length === 1
? argError.error.missingType[0].type
: argError.error.missingType.map(t => getInputTypeName(t.type)).join(' | ')
missingItems.push({
path,
type: inputTypeToJson(type, true, path.split('where.').length === 2),
isRequired: argError.error.missingType[0].isRequired,
})
}
}
const renderErrorStr = (callsite?: string) => {
const { stack, indent: indentValue, afterLines } = printStack({
callsite,
originalMethod: originalMethod || queryName,
})
const hasRequiredMissingArgsErrors = argErrors.some(
e => e.error.type === 'missingArg' && e.error.missingType[0].isRequired,
)
const hasOptionalMissingArgsErrors = argErrors.some(
e => e.error.type === 'missingArg' && !e.error.missingType[0].isRequired,
)
const hasMissingArgsErrors = hasOptionalMissingArgsErrors || hasRequiredMissingArgsErrors
let missingArgsLegend = ''
if (hasRequiredMissingArgsErrors) {
missingArgsLegend += `\n${chalk.dim('Note: Lines with ')}${chalk.reset.greenBright('+')} ${chalk.dim(
'are required',
)}`
}
if (hasOptionalMissingArgsErrors) {
if (missingArgsLegend.length === 0) {
missingArgsLegend = '\n'
}
if (hasRequiredMissingArgsErrors) {
missingArgsLegend += chalk.dim(`, lines with ${chalk.green('?')} are optional`)
} else {
missingArgsLegend += chalk.dim(`Note: Lines with ${chalk.green('?')} are optional`)
}
missingArgsLegend += chalk.dim('.')
}
const errorStr = `${stack}${indent(
printJsonWithErrors(
isTopLevelQuery ? { [topLevelQueryName]: select } : select,
keyPaths,
valuePaths,
missingItems,
),
indentValue,
).slice(indentValue)}${chalk.dim(afterLines)}
${argErrors
.filter(e => e.error.type !== 'missingArg' || e.error.missingType[0].isRequired)
.map(e => this.printArgError(e, hasMissingArgsErrors))
.join('\n')}
${fieldErrors.map(this.printFieldError).join('\n')}${missingArgsLegend}\n`
return errorStr
}
const error = new PhotonError(renderErrorStr())
// @ts-ignore
if (typeof window === 'undefined' && process.env.NODE_ENV !== 'production') {
Object.defineProperty(error, 'render', {
get: () => renderErrorStr,
enumerable: false,
})
}
throw error
}
protected printFieldError = ({ error, path }: FieldError) => {
if (error.type === 'emptySelect') {
return `The ${chalk.redBright('`select`')} statement for type ${chalk.bold(
getOutputTypeName(error.field.outputType.type),
)} must not be empty. Available options are listed in ${chalk.greenBright.dim('green')}.`
}
if (error.type === 'emptyInclude') {
return `The ${chalk.redBright('`include`')} statement for type ${chalk.bold(
getOutputTypeName(error.field.outputType.type),
)} must not be empty. Available options are listed in ${chalk.greenBright.dim('green')}.`
}
if (error.type === 'noTrueSelect') {
return `The ${chalk.redBright('`select`')} statement for type ${chalk.bold(
getOutputTypeName(error.field.outputType.type),
)} needs ${chalk.bold('at least one truthy value')}. Available options are listed in ${chalk.greenBright.dim(
'green',
)}.`
}
if (error.type === 'includeAndSelect') {
// return `The ${chalk.redBright('`select`')} statement for type ${chalk.bold(
// getOutputTypeName(error.field.outputType.type),
// )} needs ${chalk.bold('at least one truthy value')}. Available options are listed in ${chalk.greenBright.dim(
// 'green',
// )}.`
return `Please ${chalk.bold('either')} use ${chalk.greenBright('`include`')} or ${chalk.greenBright(
'`select`',
)}, but ${chalk.redBright('not both')} at the same time.`
}
if (error.type === 'invalidFieldName') {
const statement = error.isInclude ? 'include' : 'select'
const wording = error.isIncludeScalar ? 'Invalid scalar' : 'Unknown'
let str = `${wording} field ${chalk.redBright(`\`${error.providedName}\``)} for ${chalk.bold(
statement,
)} statement on model ${chalk.bold.white(
error.modelName,
)}. Available options are listed in ${chalk.greenBright.dim('green')}.`
if (error.didYouMean) {
str += ` Did you mean ${chalk.greenBright(`\`${error.didYouMean}\``)}?`
}
if (error.isIncludeScalar) {
str += `\nNote, that ${chalk.bold('include')} statements only accept relation fields.`
}
return str
}
if (error.type === 'invalidFieldType') {
const str = `Invalid value ${chalk.redBright(
`${stringifyObject(error.providedValue)}`,
)} of type ${chalk.redBright(getGraphQLType(error.providedValue, undefined))} for field ${chalk.bold(
`${error.fieldName}`,
)} on model ${chalk.bold.white(error.modelName)}. Expected either ${chalk.greenBright(
'true',
)} or ${chalk.greenBright('false')}.`
return str
}
}
protected printArgError = ({ error, path }: ArgError, hasMissingItems: boolean) => {
if (error.type === 'invalidName') {
let str = `Unknown arg ${chalk.redBright(`\`${error.providedName}\``)} in ${chalk.bold(
path.join('.'),
)} for type ${chalk.bold(error.outputType ? error.outputType.name : getInputTypeName(error.originalType))}.`
if (error.didYouMeanField) {
str += `\n→ Did you forget to wrap it with \`${chalk.greenBright('select')}\`? ${chalk.dim(
'e.g. ' + chalk.greenBright(`{ select: { ${error.providedName}: ${error.providedValue} } }`),
)}`
} else if (error.didYouMeanArg) {
str += ` Did you mean \`${chalk.greenBright(error.didYouMeanArg)}\`?`
if (!hasMissingItems) {
str += ` ${chalk.dim('Available args:')}\n` + stringifyInputType(error.originalType, true)
}
} else {
if ((error.originalType as DMMF.InputType).fields.length === 0) {
str += ` The field ${chalk.bold((error.originalType as DMMF.InputType).name)} has no arguments.`
} else if (!hasMissingItems) {
str += ` Available args:\n\n` + stringifyInputType(error.originalType, true)
}
}
return str
}
if (error.type === 'invalidType') {
let valueStr = stringifyObject(error.providedValue, { indent: ' ' })
const multilineValue = valueStr.split('\n').length > 1
if (multilineValue) {
valueStr = `\n${valueStr}\n`
}
// TODO: we don't yet support enums in a union with a non enum. This is mostly due to not implemented error handling
// at this code part.
if (error.requiredType.bestFittingType.kind === 'enum') {
return `Argument ${chalk.bold(error.argName)}: Provided value ${chalk.redBright(valueStr)}${
multilineValue ? '' : ' '
}of type ${chalk.redBright(getGraphQLType(error.providedValue))} on ${chalk.bold(
`photon.${this.children[0].name}`,
)} is not a ${chalk.greenBright(
wrapWithList(
stringifyGraphQLType(error.requiredType.bestFittingType.kind),
error.requiredType.bestFittingType.isList,
),
)}.
→ Possible values: ${(error.requiredType.bestFittingType.type as DMMF.Enum).values
.map(v => chalk.greenBright(`${stringifyGraphQLType(error.requiredType.bestFittingType.type)}.${v}`))
.join(', ')}`
}
let typeStr = '.'
if (isInputArgType(error.requiredType.bestFittingType.type)) {
typeStr = ':\n' + stringifyInputType(error.requiredType.bestFittingType.type)
}
let expected = `${error.requiredType.inputType
.map(t =>
chalk.greenBright(wrapWithList(stringifyGraphQLType(t.type), error.requiredType.bestFittingType.isList)),
)
.join(' or ')}${typeStr}`
const inputType: null | DMMF.SchemaArgInputType =
(error.requiredType.inputType.length === 2 && error.requiredType.inputType.find(t => isInputArgType(t.type))) ||
null
if (inputType) {
expected += `\n` + stringifyInputType(inputType.type, true)
}
return `Argument ${chalk.bold(error.argName)}: Got invalid value ${chalk.redBright(valueStr)}${
multilineValue ? '' : ' '
}on ${chalk.bold(`photon.${this.children[0].name}`)}. Provided ${chalk.redBright(
getGraphQLType(error.providedValue),
)}, expected ${expected}`
}
if (error.type === 'missingArg') {
return `Argument ${chalk.greenBright(error.missingName)} for ${chalk.bold(`${path.join('.')}`)} is missing.`
}
if (error.type === 'atLeastOne') {
return `Argument ${chalk.bold(path.join('.'))} of type ${chalk.bold(
error.inputType.name,
)} needs ${chalk.greenBright('at least one')} argument. Available args are listed in ${chalk.dim.green('green')}.`
}
if (error.type === 'atMostOne') {
return `Argument ${chalk.bold(path.join('.'))} of type ${chalk.bold(
error.inputType.name,
)} needs ${chalk.greenBright('exactly one')} argument, but you provided ${error.providedKeys
.map(key => chalk.redBright(key))
.join(' and ')}. Please choose one. ${chalk.dim('Available args:')} \n${stringifyInputType(
error.inputType,
true,
)}`
}
}
/**
* As we're allowing both single objects and array of objects for list inputs, we need to remove incorrect
* zero indexes from the path
* @param inputPath e.g. ['where', 'AND', 0, 'id']
* @param select select object
*/
private normalizePath(inputPath: Array<string | number>, select: any) {
const path = inputPath.slice()
const newPath: Array<string | number> = []
let key: undefined | string | number
let pointer = select
// tslint:disable-next-line:no-conditional-assignment
while ((key = path.shift()) !== undefined) {
if (!Array.isArray(pointer) && key === 0) {
continue
}
if (key === 'select') {
// TODO: Remove this logic! It shouldn't be needed
if (!pointer[key]) {
pointer = pointer.include
} else {
pointer = pointer[key]
}
} else {
pointer = pointer[key]
}
newPath.push(key)
}
return newPath
}
}
class PhotonError extends Error {}
export interface FieldArgs {
name: string
schemaField?: DMMF.SchemaField // optional as we want to even build up invalid queries to collect all errors
args?: Args
children?: Field[]
error?: InvalidFieldError
}
export class Field {
public readonly name: string
public readonly args?: Args
public readonly children?: Field[]
public readonly error?: InvalidFieldError
public readonly hasInvalidChild: boolean
public readonly hasInvalidArg: boolean
public readonly schemaField?: DMMF.SchemaField
constructor({ name, args, children, error, schemaField }: FieldArgs) {
this.name = name
this.args = args
this.children = children
this.error = error
this.schemaField = schemaField
this.hasInvalidChild = children
? children.some(child => Boolean(child.error || child.hasInvalidArg || child.hasInvalidChild))
: false
this.hasInvalidArg = args ? args.hasInvalidArg : false
}
public toString() {
let str = this.name
if (this.error) {
return str + ' # INVALID_FIELD'
}
if (this.args && this.args.args && this.args.args.length > 0) {
if (this.args.args.length === 1) {
str += `(${this.args.toString()})`
} else {
str += `(\n${indent(this.args.toString(), tab)}\n)`
}
}
if (this.children) {
str += ` {
${indent(this.children.map(String).join('\n'), tab)}
}`
}
return str
}
public collectErrors(prefix = 'select'): { fieldErrors: FieldError[]; argErrors: ArgError[] } {
const fieldErrors: FieldError[] = []
const argErrors: ArgError[] = []
if (this.error) {
fieldErrors.push({
path: [this.name],
error: this.error,
})
}
// get all errors from fields
if (this.children) {
for (const child of this.children) {
const errors = child.collectErrors(prefix)
// Field -> Field always goes through a 'select'
fieldErrors.push(...errors.fieldErrors.map(e => ({ ...e, path: [this.name, prefix, ...e.path] })))
argErrors.push(...errors.argErrors.map(e => ({ ...e, path: [this.name, prefix, ...e.path] })))
}
}
// get all errors from args
if (this.args) {
argErrors.push(...this.args.collectErrors().map(e => ({ ...e, path: [this.name, ...e.path] })))
}
return {
fieldErrors,
argErrors,
}
}
}
export class Args {
public readonly args: Arg[]
public readonly hasInvalidArg: boolean
constructor(args: Arg[] = []) {
this.args = args
this.hasInvalidArg = args ? args.some(arg => Boolean(arg.hasError)) : false
}
public toString() {
if (this.args.length === 0) {
return ''
}
return `${this.args
.map(arg => arg.toString())
.filter(a => a)
.join('\n')}`
}
public collectErrors(): ArgError[] {
if (!this.hasInvalidArg) {
return []
}
return this.args.flatMap(arg => arg.collectErrors())
}
}
/**
* Custom stringify which turns undefined into null - needed by GraphQL
* @param obj to stringify
* @param _
* @param tab
*/
function stringify(obj, _?: any, tabbing?: string | number, isEnum?: boolean) {
if (obj === undefined) {
return null
}
if (obj === null) {
return 'null'
}
if (isEnum && typeof obj === 'string') {
return obj
}
if (isEnum && Array.isArray(obj)) {
return `[${obj.join(', ')}]`
}
return JSON.stringify(obj, _, tabbing)
}
interface ArgOptions {
key: string
value: ArgValue
argType?: DMMF.ArgType // just needed to transform the ast
isEnum?: boolean
error?: InvalidArgError
schemaArg?: DMMF.SchemaArg
}
export class Arg {
public readonly key: string
public readonly value: ArgValue
public readonly error?: InvalidArgError
public readonly hasError: boolean
public readonly isEnum: boolean
public readonly schemaArg?: DMMF.SchemaArg
public readonly argType?: DMMF.ArgType
constructor({ key, value, argType, isEnum = false, error, schemaArg }: ArgOptions) {
this.key = key
this.value = value
this.argType = argType
this.isEnum = isEnum
this.error = error
this.schemaArg = schemaArg
this.hasError =
Boolean(error) ||
(value instanceof Args ? value.hasInvalidArg : false) ||
(Array.isArray(value) && value.some(v => (v instanceof Args ? v.hasInvalidArg : false)))
}
public _toString(value: ArgValue, key: string): string | undefined {
if (typeof value === 'undefined') {
return undefined
}
if (value instanceof Args) {
return `${key}: {
${indent(value.toString(), 2)}
}`
}
if (Array.isArray(value)) {
const isScalar = !(value as any[]).some(v => typeof v === 'object')
return `${key}: [${isScalar ? '' : '\n'}${indent(
(value as any[])
.map(nestedValue => {
if (nestedValue instanceof Args) {
return `{\n${indent(nestedValue.toString(), tab)}\n}`
}
return stringify(nestedValue, null, 2, this.isEnum)
})
.join(`,${isScalar ? ' ' : '\n'}`),
isScalar ? 0 : tab,
)}${isScalar ? '' : '\n'}]`
}
return `${key}: ${stringify(value, null, 2, this.isEnum)}`
}
public toString() {
return this._toString(this.value, this.key)
}
public collectErrors(): ArgError[] {
if (!this.hasError) {
return []
}
const errors: ArgError[] = []
// add the own arg
if (this.error) {
errors.push({
error: this.error,
path: [this.key],
})
}
if (Array.isArray(this.value)) {
errors.push(
...(this.value as any[]).flatMap((val, index) => {
if (!val.collectErrors) {
return []
}
return val.collectErrors().map(e => {
return { ...e, path: [this.key, index, ...e.path] }
})
}),
)
}
// collect errors of children if there are any
if (this.value instanceof Args) {
errors.push(...this.value.collectErrors().map(e => ({ ...e, path: [this.key, ...e.path] })))
}
return errors
}
}
export type ArgValue = string | boolean | number | undefined | Args | string[] | boolean[] | number[] | Args[] | null
export interface DocumentInput {
dmmf: DMMFClass
rootTypeName: 'query' | 'mutation'
rootField: string
select: any
}
export function makeDocument({ dmmf, rootTypeName, rootField, select }: DocumentInput) {
const rootType = rootTypeName === 'query' ? dmmf.queryType : dmmf.mutationType
// Create a fake toplevel field for easier implementation
const fakeRootField: DMMF.SchemaField = {
args: [],
outputType: {
isList: false,
isRequired: true,
type: rootType,
kind: 'object',
},
name: rootTypeName,
}
const children = selectionToFields(dmmf, { [rootField]: select }, fakeRootField, [rootTypeName])
return new Document(rootTypeName, children)
}
export function transformDocument(document: Document): Document {
function transformWhereArgs(args: Args) {
return new Args(
args.args.flatMap(ar => {
if (isArgsArray(ar.value)) {
// long variable name to prevent shadowing
const value = ar.value.map(argsInstance => {
return transformWhereArgs(argsInstance)
})
return new Arg({ ...ar, value })
} else if (ar.value instanceof Args) {
if (ar.schemaArg && !ar.schemaArg.isRelationFilter) {
return ar.value.args.map(a => {
return new Arg({
key: getFilterArgName(ar.key, a.key),
value: a.value,
/**
* This is an ugly hack. It assumes, that deep somewhere must be a valid inputType for
* this argument
*/
argType: deepGet(ar, ['value', 'args', '0', 'argType']),
schemaArg: a.schemaArg,
})
})
}
}
return [ar]
}),
)
}
function transformOrderArg(arg: Arg) {
if (arg.value instanceof Args) {
const orderArg = arg.value.args[0]
return new Arg({
...arg,
isEnum: true,
value: `${orderArg.key}_${orderArg.value!.toString().toUpperCase()}`,
})
}
return arg
}
return visit(document, {
Arg: {
enter(arg) {
const { argType, schemaArg } = arg
if (!argType) {
return undefined
}
if (isInputArgType(argType)) {
if (argType.isOrderType) {
return transformOrderArg(arg)
}
if (argType.isWhereType && schemaArg) {
let value = arg.value
if (isArgsArray(arg.value)) {
value = arg.value.map(val => transformWhereArgs(val))
} else if (arg.value instanceof Args) {
value = transformWhereArgs(arg.value)
}
return new Arg({ ...arg, value })
}
}
return undefined
},
},
})
}
function isArgsArray(input: any): input is Args[] {
if (Array.isArray(input)) {
return input.every(arg => arg instanceof Args)
}
return false
}
function getFilterArgName(arg: string, filter: string) {
if (filter === 'equals') {
return arg
}
return `${arg}_${convertToSnakeCase(filter)}`
}
function convertToSnakeCase(str: string): string {
return str
.split(/(?=[A-Z])/)
.join('_')
.toLowerCase()
}
export function selectionToFields(
dmmf: DMMFClass,
selection: any,
schemaField: DMMF.SchemaField,
path: string[],
): Field[] {
const outputType = schemaField.outputType.type as DMMF.OutputType
return Object.entries(selection).reduce(
(acc, [name, value]: any) => {
const field = outputType.fields.find(f => f.name === name)
if (!field) {
// if the field name is incorrect, we ignore the args and child fields altogether
acc.push(
new Field({
name,
children: [],
// @ts-ignore
error: {
type: 'invalidFieldName',
modelName: outputType.name,
providedName: name,
didYouMean: getSuggestion(name, outputType.fields.map(f => f.name)),
outputType,
},
}),
)
return acc
}
if (typeof value !== 'boolean' && field.outputType.kind === 'scalar') {
acc.push(
new Field({
name,
children: [],
error: {
type: 'invalidFieldType',
modelName: outputType.name,
fieldName: name,
providedValue: value,
},
}),
)
return acc
}
if (value === false) {
return acc
}
const transformedField = {
name: field.name,
fields: field.args,
}
const argsWithoutIncludeAndSelect = typeof value === 'object' ? omit(value, ['include', 'select']) : undefined
const args = argsWithoutIncludeAndSelect
? objectToArgs(
argsWithoutIncludeAndSelect,
transformedField,
[],
typeof field === 'string' ? undefined : (field.outputType.type as DMMF.OutputType),
)
: undefined
const isRelation = field.outputType.kind === 'object'
// TODO: use default selection for `include` again
// check for empty select
if (value) {
if (value.select && value.include) {
acc.push(
new Field({
name,
children: [
new Field({
name: 'include',
args: new Args(),
error: {
type: 'includeAndSelect',
field,
},
}),
],
}),
)
} else if (value.include) {
const keys = Object.keys(value.include)
if (keys.length === 0) {
acc.push(
new Field({
name,
children: [
new Field({
name: 'include',
args: new Args(),
error: {
type: 'emptyInclude',
field,
},
}),
],
}),
)
return acc
}
// TODO: unify with select validation logic
/**
* Error handling for `include` statements
*/
if (field.outputType.kind === 'object') {
const fieldOutputType = field.outputType.type as DMMF.OutputType
const allowedKeys = fieldOutputType.fields.filter(f => f.outputType.kind === 'object').map(f => f.name)
const invalidKeys = keys.filter(key => !allowedKeys.includes(key))
if (invalidKeys.length > 0) {
acc.push(
...invalidKeys.map(
invalidKey =>
new Field({
name: invalidKey,
children: [
new Field({
name: invalidKey,
args: new Args(),
error: {
type: 'invalidFieldName',
modelName: fieldOutputType.name,
outputType: fieldOutputType,
providedName: invalidKey,
didYouMean: getSuggestion(invalidKey, allowedKeys) || undefined,
isInclude: true,
isIncludeScalar: fieldOutputType.fields.some(f => f.name === invalidKey),
},
}),
],
// @ts-ignore
}),
),
)
return acc
}
}
} else if (value.select) {
const values = Object.values(value.select)
if (values.length === 0) {
acc.push(
new Field({
name,
children: [
new Field({
name: 'select',
args: new Args(),
error: {
type: 'emptySelect',
field,
},
}),
],
}),
)
return acc
}
// check if there is at least one truthy value
const truthyValues = values.filter(v => v)
if (truthyValues.length === 0) {
acc.push(
new Field({
name,
children: [
new Field({
name: 'select',
args: new Args(),
error: {
type: 'noTrueSelect',
field,
},
}),
],
}),
)
return acc
}
}
}
// either use select or default selection, but not both at the same time
const defaultSelection = isRelation ? getDefaultSelection(field.outputType.type as DMMF.OutputType) : null
let select = defaultSelection
if (value) {
if (value.select) {
select = value.select
} else if (value.include) {
select = deepExtend(defaultSelection, value.include)
}
}
const children =
select !== false && isRelation ? selectionToFields(dmmf, select, field, [...path, name]) : undefined
acc.push(new Field({ name, args, children, schemaField: field }))
return acc
},
[] as Field[],
)
}
function getDefaultSelection(outputType: DMMF.OutputType) {
return outputType.fields.reduce((acc, f) => {
if (f.outputType.kind === 'scalar' || f.outputType.kind === 'enum') {
acc[f.name] = true
} else {
// otherwise field is a relation. Only continue if it's an embedded type
// as normal types don't end up in the default selection
if ((f.outputType.type as DMMF.OutputType).isEmbedded) {
acc[f.name] = { select: getDefaultSelection(f.outputType.type as DMMF.OutputType) }
}
}
return acc
}, {})
}
function getInvalidTypeArg(
key: string,
value: any,
arg: DMMF.SchemaArg,
bestFittingType: DMMF.SchemaArgInputType,
): Arg {
const arrg = new Arg({
key,
value,
isEnum: bestFittingType.kind === 'enum',
argType: bestFittingType.type,
error: {
type: 'invalidType',
providedValue: value,
argName: key,
requiredType: {
inputType: arg.inputType,
bestFittingType,
},
},
})
return arrg
}
function hasCorrectScalarType(value: any, arg: DMMF.SchemaArg, inputType: DMMF.SchemaArgInputType): boolean {
const { type } = inputType
const isList = arg.inputType[0].isList
const expectedType = wrapWithList(stringifyGraphQLType(type), isList)
const graphQLType = getGraphQLType(value, type)
if (isList && graphQLType === 'List<>') {
return true
}
// DateTime is a subset of string
if (graphQLType === 'DateTime' && expectedType === 'String') {
return true
}
if (graphQLType === 'List<DateTime>' && expectedType === 'List<String>') {
return true
}
// UUID is a subset of string
if (graphQLType === 'UUID' && expectedType === 'String') {
return true
}
if (graphQLType === 'List<UUID>' && expectedType === 'List<String>') {