UNPKG

1.6 kBPlain TextView Raw
1import type {CodeKeywordDefinition, SchemaObject} from "../../types"
2import type {KeywordCxt} from "../../compile/validate"
3import {alwaysValidSchema, Type} from "../../compile/util"
4import {not, Name} from "../../compile/codegen"
5import {checkMetadata} from "./metadata"
6import {checkNullableObject} from "./nullable"
7import {typeError, _JTDTypeError} from "./error"
8
9export type JTDValuesError = _JTDTypeError<"values", "object", SchemaObject>
10
11const def: CodeKeywordDefinition = {
12 keyword: "values",
13 schemaType: "object",
14 error: typeError("object"),
15 code(cxt: KeywordCxt) {
16 checkMetadata(cxt)
17 const {gen, data, schema, it} = cxt
18 if (alwaysValidSchema(it, schema)) return
19 const [valid, cond] = checkNullableObject(cxt, data)
20 gen.if(cond)
21 gen.assign(valid, validateMap())
22 gen.elseIf(not(valid))
23 cxt.error()
24 gen.endIf()
25 cxt.ok(valid)
26
27 function validateMap(): Name | boolean {
28 const _valid = gen.name("valid")
29 if (it.allErrors) {
30 const validMap = gen.let("valid", true)
31 validateValues(() => gen.assign(validMap, false))
32 return validMap
33 }
34 gen.var(_valid, true)
35 validateValues(() => gen.break())
36 return _valid
37
38 function validateValues(notValid: () => void): void {
39 gen.forIn("key", data, (key) => {
40 cxt.subschema(
41 {
42 keyword: "values",
43 dataProp: key,
44 dataPropType: Type.Str,
45 },
46 _valid
47 )
48 gen.if(not(_valid), notValid)
49 })
50 }
51 }
52 },
53}
54
55export default def