1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('../base/Behavior');
|
7 |
|
8 | module.exports = class DataHistoryBehavior extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | Model: null,
|
13 | includes: null,
|
14 | excludes: null,
|
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 |
|
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 |
|
56 | const ArrayHelper = require('../helper/ArrayHelper');
|
57 | const ClassHelper = require('../helper/ClassHelper');
|
58 | const ActiveRecord = require('../db/ActiveRecord'); |
\ | No newline at end of file |