-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
45 lines (37 loc) · 1.21 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
module.exports = timestamps;
function timestamps(createdAtField, updatedAtField) {
if(typeof createdAtField === 'function') {
return plugin('createdAt', 'updatedAt', createdAtField);
}
else {
createdAtField = createdAtField || 'createdAt';
updatedAtField = updatedAtField || 'updatedAt';
return plugin.bind(null, createdAtField, updatedAtField);
}
}
function plugin(createdAtField, updatedAtField, Model) {
Model.attr(createdAtField, { type: 'date' });
Model.attr(updatedAtField, { type: 'date' });
Model.on('saving', function(instance, done){
var now = new Date();
if(instance.isNew()) {
instance[createdAtField](now);
}
instance[updatedAtField](now);
var set;
if ('string' === typeof instance.get(createdAtField)) {
set = {};
set[createdAtField] = new Date(instance.get(createdAtField));
instance.set(set);
}
if(done) done();
});
Model.on('initializing', function(instance, attrs) {
if ('string' === typeof attrs[createdAtField]) {
attrs[createdAtField] = new Date(attrs[createdAtField]);
}
if ('string' === typeof attrs[updatedAtField]) {
attrs[updatedAtField] = new Date(attrs[updatedAtField]);
}
});
}