nullable.ts 649 B

123456789101112131415161718192021
  1. import type {KeywordCxt} from "../../compile/validate"
  2. import {_, not, nil, Code, Name} from "../../compile/codegen"
  3. export function checkNullable(
  4. {gen, data, parentSchema}: KeywordCxt,
  5. cond: Code = nil
  6. ): [Name, Code] {
  7. const valid = gen.name("valid")
  8. if (parentSchema.nullable) {
  9. gen.let(valid, _`${data} === null`)
  10. cond = not(valid)
  11. } else {
  12. gen.let(valid, false)
  13. }
  14. return [valid, cond]
  15. }
  16. export function checkNullableObject(cxt: KeywordCxt, cond: Code): [Name, Code] {
  17. const [valid, cond_] = checkNullable(cxt, cond)
  18. return [valid, _`${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`]
  19. }