-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathtuple.js
78 lines (65 loc) · 1.71 KB
/
tuple.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"use strict";
/** Signature: function(value, field, parent, errors, context)
*/
module.exports = function ({ schema, messages }, path, context) {
const src = [];
if (schema.items != null) {
if (!Array.isArray(schema.items)) {
throw new Error(`Invalid '${schema.type}' schema. The 'items' field must be an array.`);
}
if (schema.items.length === 0) {
throw new Error(`Invalid '${schema.type}' schema. The 'items' field must not be an empty array.`);
}
}
src.push(`
if (!Array.isArray(value)) {
${this.makeError({ type: "tuple", actual: "value", messages })}
return value;
}
var len = value.length;
`);
if (schema.empty === false) {
src.push(`
if (len === 0) {
${this.makeError({ type: "tupleEmpty", actual: "value", messages })}
return value;
}
`);
}
if (schema.items != null) {
src.push(`
if (${schema.empty} !== false && len === 0) {
return value;
}
if (len !== ${schema.items.length}) {
${this.makeError({type: "tupleLength", expected: schema.items.length, actual: "len", messages})}
return value;
}
`);
src.push(`
var arr = value;
var parentField = field;
`);
for (let i = 0; i < schema.items.length; i++) {
src.push(`
value = arr[${i}];
`);
const itemPath = `${path}[${i}]`;
const rule = this.getRuleFromSchema(schema.items[i]);
const innerSource = `
arr[${i}] = ${context.async ? "await " : ""}context.fn[%%INDEX%%](arr[${i}], (parentField ? parentField : "") + "[" + ${i} + "]", parent, errors, context);
`;
src.push(this.compileRule(rule, context, itemPath, innerSource, `arr[${i}]`));
}
src.push(`
return arr;
`);
} else {
src.push(`
return value;
`);
}
return {
source: src.join("\n")
};
};