schiva 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,63 @@
1
+ const { ValidateType } = require('./validate-type');
2
+
3
+ const JSON_TYPES = ['object', 'array', 'string', 'number'];
4
+
5
+ function isJsonType(value, jsonType) {
6
+ switch (jsonType) {
7
+ case 'object':
8
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
9
+ case 'array':
10
+ return Array.isArray(value);
11
+ case 'string':
12
+ return typeof value === 'string';
13
+ default:
14
+ return typeof value === 'number';
15
+ }
16
+ }
17
+
18
+ // Checks the value with `type` only when it has the given JSON type (object, array, string or number); values of
19
+ // other types are valid. This is how JSON Schema applies keywords such as minimum or properties when no "type" is
20
+ // declared. The field name is passed through unchanged, so the wrapper does not show in messages.
21
+ class WhenType extends ValidateType {
22
+ constructor(options = {}) {
23
+ super(options);
24
+ if (!JSON_TYPES.includes(options.jsonType)) {
25
+ throw new Error(`WhenType jsonType must be one of: ${JSON_TYPES.join(', ')}`);
26
+ }
27
+ this.jsonType = options.jsonType;
28
+ this.type = options.type;
29
+ }
30
+
31
+ validate(value, fieldName) {
32
+ const result = super.validate(value, fieldName);
33
+ if (result) {
34
+ return result;
35
+ }
36
+ if (value !== undefined && value !== null && isJsonType(value, this.jsonType)) {
37
+ return this.type.validate(value, fieldName);
38
+ }
39
+ return undefined;
40
+ }
41
+
42
+ errors(value, fieldName) {
43
+ return this.validate(value, fieldName);
44
+ }
45
+
46
+ isValid(value) {
47
+ const presence = this.checkPresence(value);
48
+ if (presence !== undefined) {
49
+ return presence;
50
+ }
51
+ return !isJsonType(value, this.jsonType) || this.type.isValid(value);
52
+ }
53
+ }
54
+
55
+ function When(options) {
56
+ return new WhenType(options);
57
+ }
58
+
59
+ module.exports = {
60
+ WhenType,
61
+ When,
62
+ isJsonType,
63
+ };