Skip to content

Commit 353b202

Browse files
Hage Yaapahacksparrow
authored andcommitted
perf: improve schema validation peformance
Improve schema validation performance
1 parent 8758cb3 commit 353b202

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

packages/rest/src/validation/request-body.validator.ts

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ function convertToJsonSchema(openapiSchema: SchemaObject) {
8787
* @param schema The JSON schema used to perform the validation.
8888
* @param globalSchemas Schema references.
8989
*/
90+
91+
const compiledSchemaCache = new WeakMap();
92+
9093
function validateValueAgainstJsonSchema(
9194
// tslint:disable-next-line:no-any
9295
body: any,
@@ -102,22 +105,23 @@ function validateValueAgainstJsonSchema(
102105
allErrors: true,
103106
});
104107

105-
try {
106-
if (ajv.validate(schemaWithRef, body)) {
107-
debug('Request body passed AJV validation.');
108-
return;
109-
}
110-
} catch (err) {
111-
debug('Fails to execute AJV validation:', err);
112-
// TODO: [rfeng] Do we want to introduce a flag to disable validation
113-
// or sink validation errors?
114-
throw err;
108+
if (!compiledSchemaCache.has(jsonSchema)) {
109+
const compiled = ajv.compile(schemaWithRef);
110+
compiledSchemaCache.set(jsonSchema, compiled);
115111
}
116112

117-
debug('Invalid request body: %s', util.inspect(ajv.errors));
113+
const validate = compiledSchemaCache.get(jsonSchema);
114+
if (validate(body)) {
115+
debug('Request body passed AJV validation.');
116+
return;
117+
}
118+
119+
const validationErrors = validate.errors;
120+
121+
debug('Invalid request body: %s', util.inspect(validationErrors));
118122

119123
const error = RestHttpErrors.invalidRequestBody();
120-
error.details = _.map(ajv.errors, e => {
124+
error.details = _.map(validationErrors, e => {
121125
return {
122126
path: e.dataPath,
123127
code: e.keyword,

0 commit comments

Comments
 (0)