UNPKG

1.74 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 DataHistoryBehavior extends Base {
9
10 constructor (config) {
11 super({
12 Model: null, // [ActiveRecord]
13 includes: null, // [] tracked attribute names
14 excludes: null, // [] tracked attribute names
15 ...config
16 });
17 this.setHandler(ActiveRecord.EVENT_BEFORE_UPDATE, this.beforeUpdate);
18 this.setHandler(ActiveRecord.EVENT_AFTER_DELETE, this.afterDelete);
19 }
20
21 async beforeUpdate () {
22 for (const name of this.getAttrNames()) {
23 if (this.owner.isAttrChanged(name)) {
24 await this.createHistory(name);
25 }
26 }
27 }
28
29 async createHistory (attr) {
30 const model = ClassHelper.spawn(this.Model);
31 model.setTargetData(this.owner, attr);
32 await model.save();
33 if (model.hasError()) {
34 this.log('error', 'Model has errors', model.getErrors());
35 }
36 }
37
38 afterDelete () {
39 // delete all target object history
40 return this.Model.deleteTargetAll(this.owner);
41 }
42
43 getAttrNames () {
44 return Array.isArray(this.includes)
45 ? this.includes
46 : Array.isArray(this.excludes)
47 ? ArrayHelper.exclude(this.excludes, this.owner.ATTRS)
48 : [];
49 }
50
51 hasAttr (name) {
52 return this.getAttrNames().includes(name);
53 }
54};
55
56const ArrayHelper = require('../helper/ArrayHelper');
57const ClassHelper = require('../helper/ClassHelper');
58const ActiveRecord = require('../db/ActiveRecord');
\No newline at end of file