-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (39 loc) · 1.17 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
var _ = require('lodash');
module.exports = function( options ){
options = _.defaults( options || {}, {
operations: [ 'insert', 'update' ]
});
return function( dirac ){
var ensureTargets = function( $query, schema, next ){
module.exports.ensureTargets( $query, schema );
next();
};
Object.keys( dirac.dals ).forEach( function( table ){
options.operations.forEach( function( op ){
dirac.dals[ table ].before( op, ensureTargets );
});
});
}
};
module.exports.ensureTargets = function( $query, schema ){
var columns = Object.keys( schema ), vals, target;
var wasArray = false;
if ( $query.type === 'insert' ){
wasArray = Array.isArray( $query.values );
vals = wasArray ? $query.values : [ $query.values ];
} else if ( $query.type === 'update' ){
vals = [ $query.updates ];
}
vals = vals.map( function( val ){
val = _.pick( val, columns );
if ( Object.keys( val ).length === 0 ){
console.warn('Dirac.ensureTargets Deleted all keys!');
}
return val;
});
if ( $query.type === 'update' ){
$query.updates = vals[0];
} else {
$query.values = wasArray ? vals : vals[0];
}
};