-
Notifications
You must be signed in to change notification settings - Fork 237
/
Copy pathindex.ts
272 lines (236 loc) · 6.96 KB
/
index.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
import Ajv, {
FormatDefinition,
Format,
ErrorObject,
ValidateFunction,
} from 'ajv';
import { IJsonSchema, OpenAPIV2, OpenAPIV3 } from 'openapi-types';
const LOCAL_DEFINITION_REGEX = /^#\/([^\/]+)\/([^\/]+)$/;
export interface IOpenAPIResponseValidator {
validateResponse(
statusCode: string,
response: any
): void | OpenAPIResponseValidatorValidationError;
}
export interface OpenAPIResponseValidatorArgs {
customFormats?: {
[formatName: string]: Format | FormatDefinition<string | number>;
};
definitions?: {
[definitionName: string]: IJsonSchema;
};
components?: OpenAPIV3.ComponentsObject;
externalSchemas?: {
[index: string]: IJsonSchema;
};
loggingKey?: string;
responses: {
[responseCode: string]: {
schema: OpenAPIV2.Schema | OpenAPIV3.SchemaObject;
};
};
errorTransformer?(
openAPIResponseValidatorValidationError: OpenAPIResponseValidatorError,
ajvError: ErrorObject
): any;
}
export interface OpenAPIResponseValidatorError {
path?: string;
errorCode: string;
message: string;
}
export interface OpenAPIResponseValidatorValidationError {
message: string;
errors?: any[];
}
export default class OpenAPIResponseValidator
implements IOpenAPIResponseValidator {
private errorMapper: (ajvError: ErrorObject) => any;
private validators: {
[responseCode: string]: ValidateFunction;
};
constructor(args: OpenAPIResponseValidatorArgs) {
const loggingKey = args && args.loggingKey ? args.loggingKey + ': ' : '';
if (!args) {
throw new Error(`${loggingKey}missing args argument`);
}
if (!args.responses) {
throw new Error(`${loggingKey}args.responses must be an Object`);
}
if (!Object.keys(args.responses).length) {
throw new Error(
`${loggingKey}args.responses must contain at least 1 response object`
);
}
const errorTransformer =
typeof args.errorTransformer === 'function' && args.errorTransformer;
const v = new Ajv({
useDefaults: true,
allErrors: true,
strict: false,
// @ts-ignore TODO get Ajv updated to account for logger
logger: false,
});
this.errorMapper = errorTransformer
? makeErrorMapper(errorTransformer)
: toOpenapiValidationError;
if (args.customFormats) {
Object.keys(args.customFormats).forEach((format) => {
const func = args.customFormats[format];
if (typeof func === 'function') {
v.addFormat(format, func);
}
});
}
if (args.externalSchemas) {
Object.keys(args.externalSchemas).forEach((id) => {
v.addSchema(args.externalSchemas[id], id);
});
}
const schemas = getSchemas(
args.responses,
args.definitions,
args.components
);
this.validators = compileValidators(v, schemas);
}
public validateResponse(statusCode, response) {
let validator;
if (statusCode && statusCode in this.validators) {
validator = this.validators[statusCode];
} else if (
statusCode &&
statusCode.toString()[0] + 'XX' in this.validators
) {
validator = this.validators[statusCode.toString()[0] + 'XX'];
} else if (this.validators.default) {
validator = this.validators.default;
} else {
const message =
'An unknown status code was used and no default was provided.';
return {
message,
errors: [
{
message,
},
],
};
}
const isValid = validator({
response: response === undefined ? null : response,
});
if (!isValid) {
return {
message: 'The response was not valid.',
errors: validator.errors.map(this.errorMapper),
};
}
return undefined;
}
}
function compileValidators(v, schemas) {
const validators = {};
Object.keys(schemas).forEach((name) => {
validators[name] = v.compile(transformOpenAPIV3Definitions(schemas[name]));
});
return validators;
}
function getSchemas(responses, definitions, components) {
const schemas = {};
Object.keys(responses).forEach((name) => {
const response = responses[name];
const schema = response
? typeof response.schema === 'object'
? response.schema
: typeof response.content === 'object' &&
typeof response.content[Object.keys(response.content)[0]] ===
'object' &&
typeof response.content[Object.keys(response.content)[0]].schema ===
'object'
? response.content[Object.keys(response.content)[0]].schema
: { type: 'null' }
: { type: 'null' };
schemas[name] = {
$schema: 'http://json-schema.org/schema#',
type: 'object',
properties: {
response: schema,
},
definitions: definitions || {},
components: components || {},
};
});
return schemas;
}
function makeErrorMapper(mapper): (ajvError: ErrorObject) => any {
return (ajvError) => mapper(toOpenapiValidationError(ajvError), ajvError);
}
function toOpenapiValidationError(
error: ErrorObject
): OpenAPIResponseValidatorError {
const validationError = {
path: `instance${error.instancePath}`,
errorCode: `${error.keyword}.openapi.responseValidation`,
message: error.message,
};
validationError.path = validationError.path.replace(
/^instance\/(response\/)?/,
''
);
return validationError;
}
function recursiveTransformOpenAPIV3Definitions(object) {
// Transformations //
// OpenAPIV3 nullable
if (object.nullable === true) {
if (object.enum) {
// Enums can not be null with type null
object.oneOf = [
{ type: 'null' },
{
type: object.type,
enum: object.enum,
},
];
delete object.type;
delete object.enum;
} else if (object.type) {
object.type = [object.type, 'null'];
} else if (object.allOf) {
object.anyOf = [{ allOf: object.allOf }, { type: 'null' }];
delete object.allOf;
} else if (object.oneOf || object.anyOf) {
const arr: any[] = object.oneOf || object.anyOf;
arr.push({ type: 'null' });
}
delete object.nullable;
}
// Remove writeOnly properties from required array
if (object.properties && object.required) {
const writeOnlyProps = Object.keys(object.properties).filter(
(key) => object.properties[key].writeOnly
);
writeOnlyProps.forEach((value) => {
const index = object.required.indexOf(value);
object.required.splice(index, 1);
});
}
Object.keys(object).forEach((attr) => {
if (typeof object[attr] === 'object' && object[attr] !== null) {
recursiveTransformOpenAPIV3Definitions(object[attr]);
} else if (Array.isArray(object[attr])) {
object[attr].forEach((obj) =>
recursiveTransformOpenAPIV3Definitions(obj)
);
}
});
}
function transformOpenAPIV3Definitions(schema) {
if (typeof schema !== 'object') {
return schema;
}
const res = JSON.parse(JSON.stringify(schema));
recursiveTransformOpenAPIV3Definitions(res);
return res;
}