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