-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathSchemaValidator.ts
33 lines (30 loc) · 1.06 KB
/
SchemaValidator.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
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
import AJV from 'ajv'
import addFormats from 'ajv-formats'
import { type OpenAPIV3 } from 'openapi-types'
import { type Evaluation, Result } from './types/eval.types'
export default class SchemaValidator {
private readonly ajv: AJV
constructor (spec: OpenAPIV3.Document) {
this.ajv = new AJV({ allErrors: true, strict: true })
addFormats(this.ajv)
this.ajv.addKeyword('discriminator')
const schemas = spec.components?.schemas ?? {}
for (const key in schemas) this.ajv.addSchema(schemas[key], `#/components/schemas/${key}`)
}
validate (schema: OpenAPIV3.SchemaObject, data: any): Evaluation {
const validate = this.ajv.compile(schema)
const valid = validate(data)
return {
result: valid ? Result.PASSED : Result.FAILED,
message: valid ? undefined : this.ajv.errorsText(validate.errors)
}
}
}