1 | import type {CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject} from "../../types"
|
2 | import type {KeywordCxt} from "../../compile/validate"
|
3 | import {_, or, and, Code} from "../../compile/codegen"
|
4 | import {checkMetadata} from "./metadata"
|
5 | import {checkNullable} from "./nullable"
|
6 |
|
7 | export type JTDEnumError = ErrorObject<"enum", {allowedValues: string[]}, string[]>
|
8 |
|
9 | const error: KeywordErrorDefinition = {
|
10 | message: "must be equal to one of the allowed values",
|
11 | params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,
|
12 | }
|
13 |
|
14 | const def: CodeKeywordDefinition = {
|
15 | keyword: "enum",
|
16 | schemaType: "array",
|
17 | error,
|
18 | code(cxt: KeywordCxt) {
|
19 | checkMetadata(cxt)
|
20 | const {gen, data, schema, schemaValue, parentSchema, it} = cxt
|
21 | if (schema.length === 0) throw new Error("enum must have non-empty array")
|
22 | if (schema.length !== new Set(schema).size) throw new Error("enum items must be unique")
|
23 | let valid: Code
|
24 | const isString = _`typeof ${data} == "string"`
|
25 | if (schema.length >= it.opts.loopEnum) {
|
26 | let cond: Code
|
27 | ;[valid, cond] = checkNullable(cxt, isString)
|
28 | gen.if(cond, loopEnum)
|
29 | } else {
|
30 |
|
31 | if (!Array.isArray(schema)) throw new Error("ajv implementation error")
|
32 | valid = and(isString, or(...schema.map((value: string) => _`${data} === ${value}`)))
|
33 | if (parentSchema.nullable) valid = or(_`${data} === null`, valid)
|
34 | }
|
35 | cxt.pass(valid)
|
36 |
|
37 | function loopEnum(): void {
|
38 | gen.forOf("v", schemaValue as Code, (v) =>
|
39 | gen.if(_`${valid} = ${data} === ${v}`, () => gen.break())
|
40 | )
|
41 | }
|
42 | },
|
43 | }
|
44 |
|
45 | export default def
|