-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (84 loc) · 2.39 KB
/
index.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
79
80
81
82
83
84
85
86
87
88
89
const transformer = require('transformer');
const book = { // object to process
name: 'The Adventures of Tom Sawyer',
author: {
name: 'Mark Twain'
},
reviews: [
{
author: 'Leo Tolstoy',
text: 'Great novel',
visible: true
},
{
author: 'Fyodor Dostoyevsky',
text: 'Very interesting'
}
]
};
const schema = {
name: {
$filter: 'trim',
$validate: {
required: true,
string: true
}
},
author: {
$validate: {
required: true
},
name: {
$filter: function(value) { // you can use function for filtration
// this example has the same behaviour as built-in "trim": it trims only strings
return typeof value === 'string' ? value.trim() : value;
},
$validate: {
required: true,
string: true
}
}
},
reviews: [{ // define schema for array items
author: {
$filter: ['trim', /* another filter */], // you can use array of filters
$validate: {
required: true,
string: true
}
},
text: {
$filter: [['trim', { /* some options */ }]], // you can pass additional options to filter if needed
$validate: {
required: true,
string: true
}
},
visible: {
$default: true, // default value will be set when actual value of property is undefined
$filter: 'toBoolean' // always returns boolean
}
}]
};
const transform = function(object, schema) {
return transformer(object, schema) // you can run plugins in the order you want, but this one looks good
.default()
.filter()
.validate()
.clean()
.result;
};
transform(book, schema)
.then(result => {
// result is transformed object
console.log('Result', result);
})
.catch(err => {
if (err instanceof transformer.plugins.validate.ValidationError) {
// you have validation errors
console.log('Validation errors', err.errors);
} else {
// application error (something went wrong)
console.log('Application error', err);
}
});