UNPKG

1.14 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('../base/Behavior');
7
8module.exports = class TimestampBehavior extends Base {
9
10 constructor (config) {
11 super({
12 format: null, // 'YYYY-MM-DD HH:mm:ss';
13 createdAttr: 'createdAt', // or false
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
41const moment = require('moment');
42const ActiveRecord = require('../db/ActiveRecord');
\No newline at end of file