1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('../base/Behavior');
|
7 |
|
8 | module.exports = class TimestampBehavior extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | format: null,
|
13 | createdAttr: 'createdAt',
|
14 | updatedAttr: 'updatedAt',
|
15 | ...config
|
16 | });
|
17 | this.setHandler(ActiveRecord.EVENT_BEFORE_INSERT, this.beforeInsert);
|
18 | this.setHandler(ActiveRecord.EVENT_BEFORE_UPDATE, this.beforeUpdate);
|
19 | }
|
20 |
|
21 | beforeInsert () {
|
22 | if (this.createdAttr) {
|
23 | this.owner.set(this.createdAttr, this.formatDate());
|
24 | }
|
25 | this.beforeUpdate(...arguments);
|
26 | }
|
27 |
|
28 | beforeUpdate () {
|
29 | if (this.updatedAttr) {
|
30 | this.owner.set(this.updatedAttr, this.formatDate());
|
31 | }
|
32 | }
|
33 |
|
34 | formatDate () {
|
35 | return this.format
|
36 | ? moment().format(this.format)
|
37 | : new Date;
|
38 | }
|
39 | };
|
40 |
|
41 | const moment = require('moment');
|
42 | const ActiveRecord = require('../db/ActiveRecord'); |
\ | No newline at end of file |