source: trip-planner-front/node_modules/ajv/lib/vocabularies/jtd/enum.ts@ 8d391a1

Last change on this file since 8d391a1 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.6 KB
Line 
1import type {CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject} from "../../types"
2import type {KeywordCxt} from "../../compile/validate"
3import {_, or, and, Code} from "../../compile/codegen"
4import {checkMetadata} from "./metadata"
5import {checkNullable} from "./nullable"
6
7export type JTDEnumError = ErrorObject<"enum", {allowedValues: string[]}, string[]>
8
9const error: KeywordErrorDefinition = {
10 message: "must be equal to one of the allowed values",
11 params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,
12}
13
14const 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 /* istanbul ignore if */
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
45export default def
Note: See TracBrowser for help on using the repository browser.