-
-
Notifications
You must be signed in to change notification settings - Fork 202
/
schema.preprocessor.ts
658 lines (586 loc) 路 20.4 KB
/
schema.preprocessor.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
import Ajv from 'ajv';
import ajv = require('ajv');
import * as cloneDeep from 'lodash.clonedeep';
import * as _get from 'lodash.get';
import { createRequestAjv } from '../../framework/ajv';
import {
OpenAPIV3,
SerDesMap,
Options,
ValidateResponseOpts,
} from '../../framework/types';
interface TraversalStates {
req: TraversalState;
res: TraversalState;
}
interface TraversalState {
discriminator: object;
kind: 'req' | 'res';
path: string[];
}
interface TopLevelPathNodes {
requestBodies: Root<SchemaObject>[];
requestParameters: Root<SchemaObject>[];
responses: Root<SchemaObject>[];
}
interface TopLevelSchemaNodes extends TopLevelPathNodes {
schemas: Root<SchemaObject>[];
requestBodies: Root<SchemaObject>[];
responses: Root<SchemaObject>[];
}
class Node<T, P> {
public readonly path: string[];
public readonly parent: P;
public readonly schema: T;
constructor(parent: P, schema: T, path: string[]) {
this.path = path;
this.parent = parent;
this.schema = schema;
}
}
type SchemaObjectNode = Node<SchemaObject, SchemaObject>;
function isParameterObject(node: ParameterObject | ReferenceObject): node is ParameterObject {
return !((node as ReferenceObject).$ref);
}
function isReferenceObject(node: ArraySchemaObject | NonArraySchemaObject | ReferenceObject): node is ReferenceObject {
return !!((node as ReferenceObject).$ref);
}
function isArraySchemaObject(node: ArraySchemaObject | NonArraySchemaObject | ReferenceObject): node is ArraySchemaObject {
return !!((node as ArraySchemaObject).items);
}
function isNonArraySchemaObject(node: ArraySchemaObject | NonArraySchemaObject | ReferenceObject): node is NonArraySchemaObject {
return !isArraySchemaObject(node) && !isReferenceObject(node);
}
class Root<T> extends Node<T, T> {
constructor(schema: T, path: string[]) {
super(null, schema, path);
}
}
type ArraySchemaObject = OpenAPIV3.ArraySchemaObject;
type NonArraySchemaObject = OpenAPIV3.NonArraySchemaObject;
type OperationObject = OpenAPIV3.OperationObject;
type ParameterObject = OpenAPIV3.ParameterObject;
type ReferenceObject = OpenAPIV3.ReferenceObject;
type SchemaObject = OpenAPIV3.SchemaObject;
type Schema = ReferenceObject | SchemaObject;
if (!Array.prototype['flatMap']) {
// polyfill flatMap
// TODO remove me when dropping node 10 support
Array.prototype['flatMap'] = function (lambda) {
return Array.prototype.concat.apply([], this.map(lambda));
};
Object.defineProperty(Array.prototype, 'flatMap', { enumerable: false });
}
export const httpMethods = new Set([
'get',
'put',
'post',
'delete',
'options',
'head',
'patch',
'trace',
]);
export class SchemaPreprocessor {
private ajv: Ajv;
private apiDoc: OpenAPIV3.Document;
private apiDocRes: OpenAPIV3.Document;
private serDesMap: SerDesMap;
private responseOpts: ValidateResponseOpts;
constructor(
apiDoc: OpenAPIV3.Document,
ajvOptions: Options,
validateResponsesOpts: ValidateResponseOpts,
) {
this.ajv = createRequestAjv(apiDoc, ajvOptions);
this.apiDoc = apiDoc;
this.serDesMap = ajvOptions.serDesMap;
this.responseOpts = validateResponsesOpts;
}
public preProcess() {
const componentSchemas = this.gatherComponentSchemaNodes();
const r = this.gatherSchemaNodesFromPaths();
// Now that we've processed paths, clone a response spec if we are validating responses
this.apiDocRes = !!this.responseOpts ? cloneDeep(this.apiDoc) : null;
const schemaNodes = {
schemas: componentSchemas,
requestBodies: r.requestBodies,
responses: r.responses,
requestParameters: r.requestParameters,
};
// Traverse the schemas
this.traverseSchemas(schemaNodes, (parent, schema, opts) =>
this.schemaVisitor(parent, schema, opts),
);
return {
apiDoc: this.apiDoc,
apiDocRes: this.apiDocRes,
};
}
private gatherComponentSchemaNodes(): Root<SchemaObject>[] {
const nodes = [];
const componentSchemaMap = this.apiDoc?.components?.schemas ?? [];
for (const [id, s] of Object.entries(componentSchemaMap)) {
const schema = this.resolveSchema<SchemaObject>(s);
this.apiDoc.components.schemas[id] = schema;
const path = ['components', 'schemas', id];
const node = new Root(schema, path);
nodes.push(node);
}
return nodes;
}
private gatherSchemaNodesFromPaths(): TopLevelPathNodes {
const requestBodySchemas = [];
const requestParameterSchemas = [];
const responseSchemas = [];
for (const [p, pi] of Object.entries(this.apiDoc.paths)) {
const pathItem = this.resolveSchema<OpenAPIV3.PathItemObject>(pi);
for (const method of Object.keys(pathItem)) {
if (httpMethods.has(method)) {
const operation = <OpenAPIV3.OperationObject>pathItem[method];
// Adds path declared parameters to the schema's parameters list
this.preprocessPathLevelParameters(method, pathItem);
const path = ['paths', p, method];
const node = new Root<OpenAPIV3.OperationObject>(operation, path);
const requestBodies = this.extractRequestBodySchemaNodes(node);
const responseBodies = this.extractResponseSchemaNodes(node);
const requestParameters = this.extractRequestParameterSchemaNodes(node);
requestBodySchemas.push(...requestBodies);
responseSchemas.push(...responseBodies);
requestParameterSchemas.push(...requestParameters);
}
}
}
return {
requestBodies: requestBodySchemas,
requestParameters: requestParameterSchemas,
responses: responseSchemas,
};
}
/**
* Traverse the schema starting at each node in nodes
* @param nodes the nodes to traverse
* @param visit a function to invoke per node
*/
private traverseSchemas(nodes: TopLevelSchemaNodes, visit) {
const seen = new Set();
const recurse = (parent, node, opts: TraversalStates) => {
const schema = node.schema;
if (!schema || seen.has(schema)) return;
seen.add(schema);
if (schema.$ref) {
const resolvedSchema = this.resolveSchema<SchemaObject>(schema);
const path = schema.$ref.split('/').slice(1);
(<any>opts).req.originalSchema = schema;
(<any>opts).res.originalSchema = schema;
visit(parent, node, opts);
recurse(node, new Node(schema, resolvedSchema, path), opts);
return;
}
// Save the original schema so we can check if it was a $ref
(<any>opts).req.originalSchema = schema;
(<any>opts).res.originalSchema = schema;
visit(parent, node, opts);
if (schema.allOf) {
schema.allOf.forEach((s, i) => {
const child = new Node(node, s, [...node.path, 'allOf', i + '']);
recurse(node, child, opts);
});
} else if (schema.oneOf) {
schema.oneOf.forEach((s, i) => {
const child = new Node(node, s, [...node.path, 'oneOf', i + '']);
recurse(node, child, opts);
});
} else if (schema.anyOf) {
schema.anyOf.forEach((s, i) => {
const child = new Node(node, s, [...node.path, 'anyOf', i + '']);
recurse(node, child, opts);
});
} else if (schema.type === 'array' && schema.items) {
const child = new Node(node, schema.items, [...node.path, 'items']);
recurse(node, child, opts);
} else if (schema.properties) {
Object.entries(schema.properties).forEach(([id, cschema]) => {
const path = [...node.path, 'properties', id];
const child = new Node(node, cschema, path);
recurse(node, child, opts);
});
} else if (schema.additionalProperties) {
const child = new Node(node, schema.additionalProperties, [...node.path, 'additionalProperties']);
recurse(node, child, opts);
}
};
const initOpts = (): TraversalStates => ({
req: { discriminator: {}, kind: 'req', path: [] },
res: { discriminator: {}, kind: 'res', path: [] },
});
for (const node of nodes.schemas) {
recurse(null, node, initOpts());
}
for (const node of nodes.requestBodies) {
recurse(null, node, initOpts());
}
for (const node of nodes.responses) {
recurse(null, node, initOpts());
}
for (const node of nodes.requestParameters) {
recurse(null, node, initOpts());
}
}
private schemaVisitor(
parent: SchemaObjectNode,
node: SchemaObjectNode,
opts: TraversalStates,
) {
const pschemas = [parent?.schema];
const nschemas = [node.schema];
if (this.apiDocRes) {
const p = _get(this.apiDocRes, parent?.path);
const n = _get(this.apiDocRes, node?.path);
pschemas.push(p);
nschemas.push(n);
}
// visit the node in both the request and response schema
for (let i = 0; i < nschemas.length; i++) {
const kind = i === 0 ? 'req' : 'res';
const pschema = pschemas[i];
const nschema = nschemas[i];
const options = opts[kind];
options.path = node.path;
if (nschema) {
// This null check should no longer be necessary
this.handleSerDes(pschema, nschema, options);
this.handleReadonly(pschema, nschema, options);
this.handleWriteonly(pschema, nschema, options);
this.processDiscriminator(pschema, nschema, options);
this.removeExamples(pschema, nschema, options)
}
}
}
private processDiscriminator(parent: Schema, schema: Schema, opts: any = {}) {
const o = opts.discriminator;
const schemaObj = <OpenAPIV3.CompositionSchemaObject>schema;
const xOf = schemaObj.oneOf ? 'oneOf' : schemaObj.anyOf ? 'anyOf' : null;
if (xOf && schemaObj.discriminator?.propertyName && !o.discriminator) {
const options = schemaObj[xOf].flatMap((refObject) => {
if (refObject['$ref'] === undefined) {
return [];
}
const keys = this.findKeys(
schemaObj.discriminator.mapping,
(value) => value === refObject['$ref'],
);
const ref = this.getKeyFromRef(refObject['$ref']);
return keys.length > 0
? keys.map((option) => ({ option, ref }))
: [{ option: ref, ref }];
});
o.options = options;
o.discriminator = schemaObj.discriminator?.propertyName;
o.properties = {
...(o.properties ?? {}),
...(schemaObj.properties ?? {}),
};
o.required = Array.from(
new Set((o.required ?? []).concat(schemaObj.required ?? [])),
);
}
if (xOf) return;
if (o.discriminator) {
o.properties = {
...(o.properties ?? {}),
...(schemaObj.properties ?? {}),
};
o.required = Array.from(
new Set((o.required ?? []).concat(schemaObj.required ?? [])),
);
const ancestor: any = parent;
const ref = opts.originalSchema.$ref;
if (!ref) return;
const options = this.findKeys(
ancestor.discriminator?.mapping,
(value) => value === ref,
);
const refName = this.getKeyFromRef(ref);
if (options.length === 0 && ref) {
options.push(refName);
}
if (options.length > 0) {
const newSchema = JSON.parse(JSON.stringify(schemaObj));
const newProperties = {
...(o.properties ?? {}),
...(newSchema.properties ?? {}),
};
if (Object.keys(newProperties).length > 0) {
newSchema.properties = newProperties;
}
newSchema.required = o.required;
if (newSchema.required.length === 0) {
delete newSchema.required;
}
// Expose `_discriminator` to consumers without exposing to AJV
Object.defineProperty(ancestor, '_discriminator', {
enumerable: false,
value: ancestor._discriminator ?? {
validators: {},
options: o.options,
property: o.discriminator,
},
});
for (const option of options) {
ancestor._discriminator.validators[option] =
this.ajv.compile(newSchema);
}
}
//reset data
o.properties = {};
delete o.required;
}
}
/**
* Attach custom `x-eov-*-serdes` vendor extension for performing
* serialization (response) and deserialization (request) of data.
*
* This only applies to `type=string` schemas with a `format` that was flagged for serdes.
*
* The goal of this function is to define a JSON schema that:
* 1) Only performs the method for matching req/res (e.g. never deserialize a response)
* 2) Validates initial data THEN performs serdes THEN validates output. In that order.
* 3) Hide internal schema keywords (and its validation errors) from user.
*
* The solution is in three parts:
* 1) Remove the `type` keywords and replace it with a custom clone `x-eov-type`.
* This ensures that we control the order of type validations,
* and allows the response serialization to occur before AJV enforces the type.
* 2) Add an `x-eov-req-serdes` keyword.
* This keyword will deserialize the request string AFTER all other validations occur,
* ensuring that the string is valid before modifications.
* This keyword is only attached when deserialization is enabled.
* 3) Add an `x-eov-res-serdes` keyword.
* This keyword will serialize the response object BEFORE any other validations occur,
* ensuring the output is validated as a string.
* This keyword is only attached when serialization is enabled.
* 4) If `nullable` is set, set the type as every possible type.
* Then initial type checking will _always_ pass and the `x-eov-type` will narrow it down later.
*
* See [`createAjv`](../../framework/ajv/index.ts) for custom keyword definitions.
*
* @param {object} parent - parent schema
* @param {object} schema - schema
* @param {object} state - traversal state
*/
private handleSerDes(
parent: SchemaObject,
schema: SchemaObject,
state: TraversalState,
) {
if (
schema.type === 'string' &&
!!schema.format &&
this.serDesMap[schema.format]
) {
const serDes = this.serDesMap[schema.format];
(<any>schema)['x-eov-type'] = schema.type;
if ('nullable' in schema) {
// Ajv requires `type` keyword with `nullable` (regardless of value).
(<any>schema).type = ['string', 'number', 'boolean', 'object', 'array'];
} else {
delete schema.type;
}
if (serDes.deserialize) {
schema['x-eov-req-serdes'] = serDes;
}
if (serDes.serialize) {
schema['x-eov-res-serdes'] = serDes;
}
}
}
private removeExamples(
parent: OpenAPIV3.SchemaObject,
schema: OpenAPIV3.SchemaObject,
opts,
) {
if (schema.type !== 'object') return;
if (schema?.example) {
delete schema.example
}
if (schema?.examples) {
delete schema.examples
}
}
private handleReadonly(
parent: OpenAPIV3.SchemaObject,
schema: OpenAPIV3.SchemaObject,
opts,
) {
if (opts.kind === 'res') return;
const required = parent?.required ?? [];
const prop = opts?.path?.[opts?.path?.length - 1];
const index = required.indexOf(prop);
if (schema.readOnly && index > -1) {
// remove required if readOnly
parent.required = required
.slice(0, index)
.concat(required.slice(index + 1));
if (parent.required.length === 0) {
delete parent.required;
}
}
}
private handleWriteonly(
parent: OpenAPIV3.SchemaObject,
schema: OpenAPIV3.SchemaObject,
opts,
) {
if (opts.kind === 'req') return;
const required = parent?.required ?? [];
const prop = opts?.path?.[opts?.path?.length - 1];
const index = required.indexOf(prop);
if (schema.writeOnly && index > -1) {
// remove required if writeOnly
parent.required = required
.slice(0, index)
.concat(required.slice(index + 1));
if (parent.required.length === 0) {
delete parent.required;
}
}
}
/**
* extract all requestBodies' schemas from an operation
* @param op
*/
private extractRequestBodySchemaNodes(
node: Root<OpenAPIV3.OperationObject>,
): Root<SchemaObject>[] {
const op = node.schema;
const bodySchema = this.resolveSchema<OpenAPIV3.RequestBodyObject>(
op.requestBody,
);
op.requestBody = bodySchema;
if (!bodySchema?.content) return [];
const result: Root<SchemaObject>[] = [];
const contentEntries = Object.entries(bodySchema.content);
for (const [type, mediaTypeObject] of contentEntries) {
const mediaTypeSchema = this.resolveSchema<SchemaObject>(
mediaTypeObject.schema,
);
op.requestBody.content[type].schema = mediaTypeSchema;
const path = [...node.path, 'requestBody', 'content', type, 'schema'];
result.push(new Root(mediaTypeSchema, path));
}
return result;
}
private extractResponseSchemaNodes(
node: Root<OpenAPIV3.OperationObject>,
): Root<SchemaObject>[] {
const op = node.schema;
const responses = op.responses;
if (!responses) return;
const schemas: Root<SchemaObject>[] = [];
for (const [statusCode, response] of Object.entries(responses)) {
const rschema = this.resolveSchema<OpenAPIV3.ResponseObject>(response);
if (!rschema) {
// issue #553
// TODO the schema failed to resolve.
// This can occur with multi-file specs
// improve resolution, so that rschema resolves (use json ref parser?)
continue;
}
responses[statusCode] = rschema;
if (rschema.content) {
for (const [type, mediaType] of Object.entries(rschema.content)) {
const schema = this.resolveSchema<SchemaObject>(mediaType?.schema);
if (schema) {
rschema.content[type].schema = schema;
const path = [
...node.path,
'responses',
statusCode,
'content',
type,
'schema',
];
schemas.push(new Root(schema, path));
}
}
}
}
return schemas;
}
private extractRequestParameterSchemaNodes(
operationNode: Root<OperationObject>,
): Root<SchemaObject>[] {
return (operationNode.schema.parameters ?? []).flatMap((node) => {
const parameterObject = isParameterObject(node) ? node : undefined;
if (!parameterObject?.schema) return [];
const schema = isNonArraySchemaObject(parameterObject.schema) ?
parameterObject.schema :
undefined;
if (!schema) return [];
return new Root(schema, [
...operationNode.path,
'parameters',
parameterObject.name,
parameterObject.in
]);
});
}
private resolveSchema<T>(schema): T {
if (!schema) return null;
const ref = schema?.['$ref'];
let res = (ref ? this.ajv.getSchema(ref)?.schema : schema) as T;
if (ref && !res) {
const path = ref.split('/').join('.');
const p = path.substring(path.indexOf('.') + 1);
res = _get(this.apiDoc, p);
}
return res;
}
/**
* add path level parameters to the schema's parameters list
* @param pathItemKey
* @param pathItem
*/
private preprocessPathLevelParameters(
pathItemKey: string,
pathItem: OpenAPIV3.PathItemObject,
) {
const parameters = pathItem.parameters ?? [];
if (parameters.length === 0) return;
const v = this.resolveSchema<OpenAPIV3.OperationObject>(
pathItem[pathItemKey],
);
if (v === parameters) return;
v.parameters = v.parameters || [];
const match = (
pathParam: OpenAPIV3.ReferenceObject | OpenAPIV3.ParameterObject,
opParam: OpenAPIV3.ReferenceObject | OpenAPIV3.OperationObject,
) =>
// if name or ref exists and are equal
(opParam['name'] && opParam['name'] === pathParam['name']) ||
(opParam['$ref'] && opParam['$ref'] === pathParam['$ref']);
// Add Path level query param to list ONLY if there is not already an operation-level query param by the same name.
for (const param of parameters) {
if (!v.parameters.some((vparam) => match(param, vparam))) {
v.parameters.push(param);
}
}
}
private findKeys(object, searchFunc): string[] {
const matches = [];
if (!object) {
return matches;
}
const keys = Object.keys(object);
for (let i = 0; i < keys.length; i++) {
if (searchFunc(object[keys[i]])) {
matches.push(keys[i]);
}
}
return matches;
}
getKeyFromRef(ref) {
return ref.split('/components/schemas/')[1];
}
}