-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (57 loc) · 2.18 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
'use strict';
const extend = require( 'extend' );
module.exports = conform;
function conform( options ) {
// ensure object has all fields from model
let object = extend( true, Array.isArray( options.model ) ? [] : {}, options.model, options.object );
for ( let field in object ) {
if ( !object.hasOwnProperty( field ) ) {
continue;
}
if ( !options.model.hasOwnProperty( field ) ) {
delete object[ field ];
continue;
}
ensureObjectsAreObjects( {
model: options.model,
field: field,
object: object
} );
ensureArraysAreArrays( {
model: options.model,
field: field,
object: object
} );
ensureNestedObjectsAreConformed( {
model: options.model,
field: field,
object: object,
nested: options.nested,
} );
}
return object;
}
function ensureObjectsAreObjects( options ) {
if ( options.model[ options.field ] !== null &&
typeof options.model[ options.field ] === 'object' &&
!Array.isArray( options.model[ options.field ] ) &&
( options.object[ options.field ] === null || typeof options.object[ options.field ] !== 'object' ) ) {
options.object[ options.field ] = extend( true, {}, options.model[ options.field ] );
}
}
function ensureArraysAreArrays( options ) {
if ( Array.isArray( options.model[ options.field ] ) && !Array.isArray( options.object[ options.field ] ) ) {
options.object[ options.field ] = extend( true, [], options.model[ options.field ] );
}
}
function ensureNestedObjectsAreConformed( options ) {
if ( options.model[ options.field ] !== null &&
typeof options.model[ options.field ] === 'object' &&
( !options.nested || typeof options.nested[ options.field ] === 'undefined' || options.nested[ options.field ] ) ) {
options.object[ options.field ] = conform( {
object: options.object[ options.field ],
model: options.model[ options.field ],
nested: options.nested ? options.nested[ options.field ] : null
} );
}
}