source: imaps-frontend/node_modules/ajv/lib/vocabularies/validation/enum.ts@ 79a0317

main
Last change on this file since 79a0317 was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 3 days ago

F4 Finalna Verzija

  • Property mode set to 100644
File size: 1.8 KB
Line 
1import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
2import type {KeywordCxt} from "../../compile/validate"
3import {_, or, Name, Code} from "../../compile/codegen"
4import {useFunc} from "../../compile/util"
5import equal from "../../runtime/equal"
6
7export type EnumError = ErrorObject<"enum", {allowedValues: any[]}, any[] | {$data: 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 $data: true,
18 error,
19 code(cxt: KeywordCxt) {
20 const {gen, data, $data, schema, schemaCode, it} = cxt
21 if (!$data && schema.length === 0) throw new Error("enum must have non-empty array")
22 const useLoop = schema.length >= it.opts.loopEnum
23 let eql: Name | undefined
24 const getEql = (): Name => (eql ??= useFunc(gen, equal))
25
26 let valid: Code
27 if (useLoop || $data) {
28 valid = gen.let("valid")
29 cxt.block$data(valid, loopEnum)
30 } else {
31 /* istanbul ignore if */
32 if (!Array.isArray(schema)) throw new Error("ajv implementation error")
33 const vSchema = gen.const("vSchema", schemaCode)
34 valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i)))
35 }
36 cxt.pass(valid)
37
38 function loopEnum(): void {
39 gen.assign(valid, false)
40 gen.forOf("v", schemaCode as Code, (v) =>
41 gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())
42 )
43 }
44
45 function equalCode(vSchema: Name, i: number): Code {
46 const sch = schema[i]
47 return typeof sch === "object" && sch !== null
48 ? _`${getEql()}(${data}, ${vSchema}[${i}])`
49 : _`${data} === ${sch}`
50 }
51 },
52}
53
54export default def
Note: See TracBrowser for help on using the repository browser.