UNPKG

1.1 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 UserStampBehavior extends Base {
9
10 constructor (config) {
11 super({
12 creatorAttr: 'creator', // or false
13 editorAttr: 'editor', // or false
14 ...config
15 });
16 this.setHandler(ActiveRecord.EVENT_BEFORE_INSERT, this.beforeInsert);
17 this.setHandler(ActiveRecord.EVENT_BEFORE_UPDATE, this.beforeUpdate);
18 }
19
20 beforeInsert () {
21 if (this.creatorAttr) {
22 this.owner.set(this.creatorAttr, this.getUserId());
23 }
24 this.beforeUpdate();
25 }
26
27 beforeUpdate () {
28 if (this.editorAttr) {
29 this.owner.set(this.editorAttr, this.getUserId());
30 }
31 }
32
33 getUserId () {
34 return this.owner.user instanceof WebUser
35 ? this.owner.user.getId()
36 : null;
37 }
38};
39
40const ActiveRecord = require('../db/ActiveRecord');
41const WebUser = require('../security/WebUser');
\No newline at end of file