-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathenum.ts
More file actions
52 lines (48 loc) · 1.45 KB
/
enum.ts
File metadata and controls
52 lines (48 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { Keyword, JsonSchemaValidatorParams } from "../Keyword";
import { SchemaNode } from "../SchemaNode";
import { getTypeOf } from "../utils/getTypeOf";
const KEYWORD = "enum";
export const enumKeyword: Keyword = {
id: KEYWORD,
keyword: KEYWORD,
parse: parseEnum,
addValidate: (node) => node.enum != null,
validate: validateEnum
};
export function parseEnum(node: SchemaNode) {
const { schema } = node;
if (schema[KEYWORD] == null) {
return;
}
if (!Array.isArray(schema[KEYWORD])) {
return node.createError("schema-error", {
pointer: `${node.schemaLocation}/${KEYWORD}`,
schema,
value: schema[KEYWORD],
message: `Keyword '${KEYWORD}' must be an array - received '${typeof schema[KEYWORD]}'`
});
}
node.enum = schema[KEYWORD];
}
function validateEnum({ node, data, pointer = "#" }: JsonSchemaValidatorParams) {
if (node.enum == null) {
return;
}
const type = getTypeOf(data);
if (type === "object" || type === "array") {
const valueStr = JSON.stringify(data);
for (const e of node.enum) {
if (JSON.stringify(e) === valueStr) {
return undefined;
}
}
} else if (node.enum.includes(data)) {
return undefined;
}
return node.createError("enum-error", {
pointer,
schema: node.schema,
value: data,
values: node.enum
});
}