forked from clarkbw/loopback-ds-timestamp-mixin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime-stamp.js
31 lines (24 loc) · 1.11 KB
/
time-stamp.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
var debug = require('debug')('loopback-ds-timestamp-mixin');
module.exports = function timestamp(Model, options) {
'use strict';
debug('TimeStamp mixin for Model %s', Model.modelName);
var createdAt = options.createdAt || 'createdAt';
var updatedAt = options.updatedAt || 'updatedAt';
var required = options.required === undefined ? true : options.required;
debug('createdAt', createdAt, options.createdAt);
debug('updatedAt', updatedAt, options.updatedAt);
Model.defineProperty(createdAt, { type: Date, required: required, defaultFn: 'now' });
Model.defineProperty(updatedAt, { type: Date, required: required });
Model.observe('before save', function event(ctx, next) {
debug('ctx.options', ctx.options);
if (ctx.options && ctx.options.skipUpdatedAt) { return next(); }
if (ctx.instance) {
debug('%s.%s before save: %s', ctx.Model.modelName, updatedAt, ctx.instance.id);
ctx.instance[updatedAt] = new Date();
} else {
debug('%s.%s before update matching %j', ctx.Model.pluralModelName, updatedAt, ctx.where);
ctx.data[updatedAt] = new Date();
}
next();
});
};