Skip to content

Commit d1bb00f

Browse files
committed
Add modifiers
1 parent 50cc5f7 commit d1bb00f

File tree

4 files changed

+46
-3
lines changed

4 files changed

+46
-3
lines changed

lib/modelate.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const util = require('./util');
22

33
const models = require('./model').models;
44
const validate = require('./validate').check;
5+
const modify = require('./modify').check;
56

67
/**
78
* Create a new modelate, validating all properties
@@ -19,6 +20,10 @@ function modelate(data, opts) {
1920
const result = util.clone(model) || {};
2021

2122
for (const prop in model) {
23+
// Step 1: Apply the modifiers
24+
data[prop] = modify(data[prop], model[prop]);
25+
26+
// Step 2: validate the result
2227
if (validate(data[prop], model[prop])) {
2328
result[prop] = data[prop];
2429
} else {
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88
*/
99
function isValid(data, model) {
1010
if (!model.default) {
11-
return true;
11+
return null;
1212
}
1313

1414
if (!data) {
15-
data = model.default;
15+
return model.default;
1616
}
1717
}
1818

lib/modify.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
2+
// Add modifier names here
3+
const modifiers = ['default'];
4+
5+
// Turn modifier names to modifier instances.
6+
for (let i = 0; i < modifiers.length; i++) {
7+
modifiers[i] = modifier(modifiers[i]);
8+
}
9+
10+
/**
11+
* Validate
12+
*
13+
* @param data {Object} Data to validate
14+
* @param model {Object} Model to apply validations
15+
*/
16+
function modify(data, model) {
17+
for (let i = 0; i < modifiers.length; i++) {
18+
const newValue = modifiers[i].check(data, model);
19+
return newValue ? newValue : data;
20+
}
21+
22+
return true;
23+
}
24+
25+
/**
26+
* Create new modifier instances
27+
*/
28+
function modifier(name) {
29+
return {
30+
name: name,
31+
check: require('./modifiers/' + name),
32+
};
33+
}
34+
35+
module.exports = {
36+
modifiers: modifiers,
37+
check: modify
38+
};

lib/validate.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11

22
// Add validator names here
3-
const validators = ['type', 'length', 'value', 'func', 'model', 'date', 'value', 'default'];
3+
const validators = ['type', 'length', 'value', 'func', 'model', 'date', 'value'];
44

55
// Turn validator names to validator instances.
66
for (let i = 0; i < validators.length; i++) {

0 commit comments

Comments
 (0)