@@ -87,6 +87,9 @@ function convertToJsonSchema(openapiSchema: SchemaObject) {
87
87
* @param schema The JSON schema used to perform the validation.
88
88
* @param globalSchemas Schema references.
89
89
*/
90
+
91
+ const compiledSchemaCache = new WeakMap ( ) ;
92
+
90
93
function validateValueAgainstJsonSchema (
91
94
// tslint:disable-next-line:no-any
92
95
body : any ,
@@ -102,22 +105,23 @@ function validateValueAgainstJsonSchema(
102
105
allErrors : true ,
103
106
} ) ;
104
107
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 ) ;
115
111
}
116
112
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 ) ) ;
118
122
119
123
const error = RestHttpErrors . invalidRequestBody ( ) ;
120
- error . details = _ . map ( ajv . errors , e => {
124
+ error . details = _ . map ( validationErrors , e => {
121
125
return {
122
126
path : e . dataPath ,
123
127
code : e . keyword ,
0 commit comments