This repository has been archived by the owner on Jun 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
validate.ts
530 lines (467 loc) · 13 KB
/
validate.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
import {dirname, basename} from 'path';
import {
GraphQLType,
GraphQLNonNull,
GraphQLList,
GraphQLString,
GraphQLInt,
GraphQLFloat,
GraphQLBoolean,
GraphQLLeafType,
isEnumType,
isListType,
isNonNullType,
isObjectType,
isScalarType,
} from 'graphql';
import {GraphQLProjectConfig} from 'graphql-config';
import {resolveProjectName} from 'graphql-config-utilities';
import {AST, Field, Operation} from 'graphql-tool-utilities';
export type KeyPath = string;
export interface Fixture {
path: string;
content: any;
}
export interface Error {
keyPath?: KeyPath;
message: string;
}
export interface GraphQLProjectAST {
config: GraphQLProjectConfig;
ast: AST;
}
export interface FoundOperation {
lookForOperationName: string;
operation: Operation;
projectAST: GraphQLProjectAST;
}
export class MissingOperationError extends Error {
constructor(
{path}: Fixture,
lookForOperationNames: string[],
projectASTCollection: GraphQLProjectAST[],
) {
super(
[
`Could not find a matching operation for '${path}'`,
`(looked for ${lookForOperationNames.join(', ')}).`,
`Make sure to put your fixture in a folder named the same as the operation,`,
`or add an '${OPERATION_MARKER}' key indicating the operation.`,
`Available operations: ${projectASTCollection
.flatMap(({ast: {operations}}) => Object.keys(operations))
.join(', ')}`,
].join(' '),
);
}
}
export class AmbiguousOperationNameError extends Error {
constructor({path}: Fixture, foundOperations: FoundOperation[]) {
super(
[
`Ambiguous operation name found for '${path}'`,
`(found ${Array.from(
new Set(
foundOperations.map(
({lookForOperationName}) => lookForOperationName,
),
),
).join(', ')})`,
`in projects:`,
`${foundOperations
.map(({projectAST: {config}}) => resolveProjectName(config))
.join(', ')}.`,
`Try renaming the operation in one of the projects listed and updating`,
`the fixture folder name or use an '${OPERATION_MARKER}' key indicating`,
`the new operation name.`,
].join(' '),
);
}
}
export interface Validation {
fixturePath: string;
operationName?: string;
operationType?: string;
operationPath?: string;
validationErrors: Error[];
}
const OPERATION_MARKER = '@operation';
function normalizeOperationName(operationName: string): string;
function normalizeOperationName(
operationName: string | undefined,
): string | undefined;
function normalizeOperationName(operationName: string | undefined) {
return operationName
? operationName.replace(/(Query|Mutation|Subscription)$/i, '')
: undefined;
}
export function getOperationNames(fixture: Fixture): string[] {
const fixtureDirectoryName = basename(dirname(fixture.path));
const operationMarkerName: string | undefined =
fixture.content[OPERATION_MARKER];
return Array.from(
new Set([
fixtureDirectoryName,
operationMarkerName,
normalizeOperationName(fixtureDirectoryName),
normalizeOperationName(operationMarkerName),
]),
).filter(
(operationName): operationName is string =>
typeof operationName === 'string',
);
}
export function findOperations(
lookForOperationNames: string[],
projectASTCollection: GraphQLProjectAST[],
) {
return projectASTCollection
.map<FoundOperation | null>((projectAST) => {
for (const lookForOperationName of lookForOperationNames) {
const operation = projectAST.ast.operations[lookForOperationName];
if (operation) {
return {
lookForOperationName,
operation,
projectAST,
};
}
}
return null;
})
.filter((match): match is FoundOperation => Boolean(match));
}
export function getOperationForFixture(
fixture: Fixture,
projectASTCollection: GraphQLProjectAST[],
) {
const lookForOperationNames = getOperationNames(fixture);
const operations = findOperations(
lookForOperationNames,
projectASTCollection,
);
if (operations.length === 0) {
throw new MissingOperationError(
fixture,
lookForOperationNames,
projectASTCollection,
);
}
if (operations.length > 1) {
throw new AmbiguousOperationNameError(fixture, operations);
}
return operations[0];
}
export interface FixtureOperation {
fixture: Fixture;
operation: Operation;
operationName: string;
}
export function validateFixture(
fixture: Fixture,
ast: AST,
operation: Operation,
): Validation {
const {fields = [], filePath, operationType} = operation;
const value = {...fixture.content};
delete value[OPERATION_MARKER];
return {
fixturePath: fixture.path,
operationName: operation.operationName,
operationType,
operationPath: filePath === 'GraphQL request' ? undefined : filePath,
validationErrors: fields.reduce((allErrors: Error[], field) => {
return allErrors.concat(
validateValueAgainstFieldDescription(
value[field.responseName],
field,
'',
ast,
),
);
}, []),
};
}
function validateValueAgainstFieldDescription(
value: any,
fieldDescription: Field,
parentKeyPath: string,
ast: AST,
): Error[] {
const {type, responseName} = fieldDescription;
const keyPath = updateKeyPath(parentKeyPath, responseName);
const typeErrors = validateValueAgainstType(value, type, keyPath, {
shallow: true,
});
if (typeErrors.length > 0) {
return typeErrors;
}
return Array.isArray(value)
? validateListAgainstFieldDescription(
value,
fieldDescription,
type as GraphQLList<GraphQLType>,
keyPath,
ast,
)
: validateValueAgainstObjectFieldDescription(
value,
fieldDescription,
keyPath,
ast,
);
}
function validateValueAgainstObjectFieldDescription(
value: any,
fieldDescription: Field,
keyPath: string,
ast: AST,
) {
if (value == null || typeof value !== 'object' || Array.isArray(value)) {
return [];
}
const {fields = [], fragmentSpreads = [], type} = fieldDescription;
const fragmentFields: Field[] = [];
if (fragmentSpreads) {
fragmentSpreads
.map((spread) => ast.fragments[spread])
.forEach((fragment) => {
fragment.fields.forEach((field) => {
if (fields.some(({fieldName}) => fieldName === field.fieldName)) {
return;
}
const isGuaranteedTypeMatch = fragment.possibleTypes.includes(
makeTypeNullable(type),
);
fragmentFields.push(
isGuaranteedTypeMatch
? field
: {...field, type: makeTypeNullable(field.type)},
);
});
});
}
return validateValueAgainstFields(
value,
fields.concat(fragmentFields),
keyPath,
ast,
);
}
function makeTypeNullable(type: GraphQLType) {
return isNonNullType(type) ? type.ofType : type;
}
function validateListAgainstFieldDescription(
value: any[],
fieldDescription: Field,
type: GraphQLList<GraphQLType>,
keyPath: string,
ast: AST,
): Error[] {
const itemType = isNonNullType(type)
? (type as GraphQLNonNull<GraphQLList<GraphQLType>>).ofType.ofType
: (type as GraphQLList<GraphQLType>).ofType;
return value.reduce((allErrors, item, index) => {
const itemKeyPath = updateKeyPath(keyPath, index);
const itemTypeErrors = validateValueAgainstType(
item,
itemType,
itemKeyPath,
{shallow: true},
);
if (itemTypeErrors.length > 0) {
return allErrors.concat(itemTypeErrors);
}
return Array.isArray(item)
? allErrors.concat(
validateListAgainstFieldDescription(
item,
fieldDescription,
itemType as GraphQLList<GraphQLType>,
itemKeyPath,
ast,
),
)
: allErrors.concat(
validateValueAgainstObjectFieldDescription(
item,
fieldDescription,
itemKeyPath,
ast,
),
);
}, []);
}
function validateValueAgainstFields(
value: {[key: string]: any},
fields: Field[],
keyPath: KeyPath,
ast: AST,
) {
const finalValue = value || {};
const excessFields = Object.keys(finalValue)
.filter((key) => fields.every(({responseName}) => key !== responseName))
.map((key) => error(keyPath, `has key '${key}' not present in the query`));
return fields.reduce((allErrors, field) => {
return allErrors.concat(
validateValueAgainstFieldDescription(
finalValue[field.responseName],
field,
keyPath,
ast,
),
);
}, excessFields);
}
interface TypeValidationOptions {
shallow: boolean;
}
function validateValueAgainstType(
value: any,
type: GraphQLType,
keyPath: KeyPath,
options: TypeValidationOptions = {shallow: false},
): Error[] {
const {shallow} = options;
if (isNonNullType(type)) {
return value == null
? [error(keyPath, `should be non-null but was ${String(value)}`)]
: validateValueAgainstType(value, type.ofType, keyPath, options);
}
if (value === null) {
return [];
}
const valueType = typeof value;
if (isListType(type)) {
if (!Array.isArray(value)) {
return [
error(
keyPath,
`should be an array (or null), but was ${articleForType(
valueType,
)} ${valueType}`,
),
];
}
return shallow
? []
: value.reduce(
(allErrors: Error[], item, index) =>
allErrors.concat(
validateValueAgainstType(
item,
type.ofType,
updateKeyPath(keyPath, index),
options,
),
),
[],
);
}
if (value === undefined) {
const typeName = nameForType(type as GraphQLLeafType);
return [
error(
keyPath,
`should be ${articleForType(
typeName,
)} ${typeName} (or null), but was undefined`,
),
];
}
if (isObjectType(type)) {
if (valueType === 'object') {
if (shallow) {
return [];
} else {
const fields = type.getFields();
return Object.keys(value).reduce((fieldErrors: Error[], key) => {
const fieldKeyPath = updateKeyPath(keyPath, key);
return fields[key] == null
? fieldErrors.concat([
error(
fieldKeyPath,
`does not exist on type ${
type.name
} (available fields: ${Object.keys(fields).join(', ')})`,
),
])
: fieldErrors.concat(
validateValueAgainstType(
value[key],
fields[key].type,
fieldKeyPath,
options,
),
);
}, []);
}
} else {
return [error(keyPath, `should be an object but was a ${valueType}`)];
}
}
if (type === GraphQLString) {
return valueType === 'string'
? []
: [error(keyPath, `should be a string but was a ${valueType}`)];
} else if (type === GraphQLInt) {
if (typeof value === 'number') {
return Number.isInteger(value)
? []
: [error(keyPath, 'should be an integer but was a float')];
}
return [error(keyPath, `should be an integer but was a ${valueType}`)];
} else if (type === GraphQLFloat) {
return Number.isNaN(value)
? [error(keyPath, `should be a float but was a ${valueType}`)]
: [];
} else if (type === GraphQLBoolean) {
return typeof value === 'boolean'
? []
: [error(keyPath, `should be a boolean but was a ${valueType}`)];
}
if (isScalarType(type)) {
return type.parseValue(value) == null
? [error(keyPath, `value does not match scalar ${nameForType(type)}`)]
: [];
}
if (isEnumType(type)) {
return type.parseValue(value) == null
? [
error(
keyPath,
`value does not match enum ${nameForType(
type,
)} (available values: ${type
.getValues()
.map((enumValue) => enumValue.value)
.join(', ')})`,
),
]
: [];
}
return [];
}
const CUSTOM_NAMES = {
[GraphQLBoolean.name]: 'boolean',
[GraphQLFloat.name]: 'float',
[GraphQLInt.name]: 'integer',
[GraphQLString.name]: 'string',
};
function nameForType(type: GraphQLLeafType) {
return Object.prototype.hasOwnProperty.call(CUSTOM_NAMES, type.name)
? CUSTOM_NAMES[type.name]
: type.name;
}
const TYPES_WITH_ARTICLE_AN = ['object', 'integer', 'array'];
function articleForType(type: string) {
return TYPES_WITH_ARTICLE_AN.includes(type) ? 'an' : 'a';
}
function updateKeyPath(keyPath: KeyPath, newKey: string | number) {
if (typeof newKey === 'number') {
return `${keyPath}[${newKey}]`;
}
return keyPath ? `${keyPath}.${newKey}` : newKey;
}
function error(keyPath: KeyPath, message: string): Error {
return {keyPath, message};
}