elements.ts 976 B

1234567891011121314151617181920212223242526272829303132
  1. import type {CodeKeywordDefinition, SchemaObject} from "../../types"
  2. import type {KeywordCxt} from "../../compile/validate"
  3. import {alwaysValidSchema} from "../../compile/util"
  4. import {validateArray} from "../code"
  5. import {_, not} from "../../compile/codegen"
  6. import {checkMetadata} from "./metadata"
  7. import {checkNullable} from "./nullable"
  8. import {typeError, _JTDTypeError} from "./error"
  9. export type JTDElementsError = _JTDTypeError<"elements", "array", SchemaObject>
  10. const def: CodeKeywordDefinition = {
  11. keyword: "elements",
  12. schemaType: "object",
  13. error: typeError("array"),
  14. code(cxt: KeywordCxt) {
  15. checkMetadata(cxt)
  16. const {gen, data, schema, it} = cxt
  17. if (alwaysValidSchema(it, schema)) return
  18. const [valid] = checkNullable(cxt)
  19. gen.if(not(valid), () =>
  20. gen.if(
  21. _`Array.isArray(${data})`,
  22. () => gen.assign(valid, validateArray(cxt)),
  23. () => cxt.error()
  24. )
  25. )
  26. cxt.ok(valid)
  27. },
  28. }
  29. export default def