/
sample.js
77 lines (74 loc) · 2.22 KB
/
sample.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
/* eslint-disable no-console */
const { ObjectChecker } = require('is-valid-object');
const schema = {
// declare the properties from the other object and describe their type
first: {
type: 'string',
// the maximum and the minimum length allowed for the string
maxLength: 25,
minLength: 1,
},
second: {
type: 'integer',
// the maximum and the minimum range allowed for the number
minRange: 10,
maxRange: 500,
},
third: {
type: 'float',
// the maximum and the minimum range allowed for the number
minRange: 10,
maxRange: 500,
},
fourth: {
// schema can recusively iterate objects and validate them
type: 'object',
// the properties follow the same rules as regular keys
properties: {
fifth: {
type: 'string',
},
sixth: {
type: 'any',
},
},
},
eighth: {
// for arrays, the elements can be validated with the type, minimum and maxiumum arr length
type: 'array',
minLength: 2,
maxLength: 5,
elements_type: 'integer',
},
ninth: {
// boolean variables can be checked if they're either true or false
type: 'bool',
},
};
// declare the object which needs to be checked
// this will be in-line with the schema declared earlier
const toBeChecked = {
first: 'this is a string',
second: 100,
// beware that 50.0 is still integer and not float in js
third: 50.52,
fourth: {
fifth: 'hello string',
sixth: {
seventh: "doesn't matter",
},
},
eighth: [1234, 1234, 1234],
ninth: true,
};
console.time('object-checker');
const checker = new ObjectChecker();
// arg one is the object to be checked and arg two is the schema for that object
// @returns {
// schema, -> the schema that was sent in the arg two
// validatedObject: object, -> the same object which was provided as arg one
// }
// the method will throw exceptions with { error: "some message" } if any of the items don't confirm
// to the specified shcema
checker.check(toBeChecked, schema);
console.timeEnd('object-checker');