Created
October 9, 2022 09:08
-
-
Save leegilmorecode/650fa14222f0b19344e33b7c15dab4e2 to your computer and use it in GitHub Desktop.
validate.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Ajv from 'ajv'; | |
import addFormats from 'ajv-formats'; | |
const ajvOptions = { | |
allErrors: true, | |
}; | |
// as this is not a monorepo and an example repo only we are using a typescript path alias | |
// whereas this would typically be published to npm and reused in all domain service | |
export function validate( | |
obj: Record<string, any>, | |
schema: Record<string, any>, | |
key: string, | |
ref: string | |
): void { | |
const ajv = new Ajv(ajvOptions); | |
addFormats(ajv); | |
ajv.addVocabulary(['openapi', 'info', 'paths', 'components']); | |
ajv.addSchema(schema, key); | |
const valid = ajv.validate({ $ref: ref }, obj); | |
if (!valid) { | |
const errorMessage = JSON.stringify(ajv.errors); | |
throw new Error(errorMessage); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment