instance.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import Ajv, {AnySchema, AnyValidateFunction, ErrorObject} from "../core"
  2. import standaloneCode from "."
  3. import * as requireFromString from "require-from-string"
  4. export default class AjvPack {
  5. errors?: ErrorObject[] | null // errors from the last validation
  6. constructor(readonly ajv: Ajv) {}
  7. validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown> {
  8. return Ajv.prototype.validate.call(this, schemaKeyRef, data)
  9. }
  10. compile<T = unknown>(schema: AnySchema, meta?: boolean): AnyValidateFunction<T> {
  11. return this.getStandalone(this.ajv.compile<T>(schema, meta))
  12. }
  13. getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {
  14. const v = this.ajv.getSchema<T>(keyRef)
  15. if (!v) return undefined
  16. return this.getStandalone(v)
  17. }
  18. private getStandalone<T = unknown>(v: AnyValidateFunction<T>): AnyValidateFunction<T> {
  19. return requireFromString(standaloneCode(this.ajv, v)) as AnyValidateFunction<T>
  20. }
  21. addSchema(...args: Parameters<typeof Ajv.prototype.addSchema>): AjvPack {
  22. this.ajv.addSchema.call(this.ajv, ...args)
  23. return this
  24. }
  25. addKeyword(...args: Parameters<typeof Ajv.prototype.addKeyword>): AjvPack {
  26. this.ajv.addKeyword.call(this.ajv, ...args)
  27. return this
  28. }
  29. }