-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (41 loc) · 1.11 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
var merge = require('lodash.merge');
module.exports = function timestampPlugin(schema, options) {
options = merge({
declaration: {
created: {
key: 'created',
config: {
type: Date
}
},
updated: {
key: 'updated',
config: {
type: Date
}
}
}
}, options);
if (!options.declaration.created && !options.declaration.updated) {
throw new Error('"created" and "updated" are disabled');
}
['created', 'updated'].forEach(function eachKey(key) {
var declaration;
var config = {};
if (!options.declaration[key]) {
return;
}
declaration = options.declaration[key];
config[declaration.key] = declaration.config;
schema.add(config);
});
schema.pre('save', function handlePreSave(next) {
if (options.declaration.updated) {
this[options.declaration.updated.key] = Date.now();
}
if (options.declaration.created && !this[options.declaration.created.key]) {
this[options.declaration.created.key] = this[options.declaration.updated.key] || Date.now();
}
next();
});
};