-
Notifications
You must be signed in to change notification settings - Fork 3
/
SortOrderBehavior.js
63 lines (55 loc) · 1.78 KB
/
SortOrderBehavior.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
*/
'use strict';
const Base = require('../base/Behavior');
module.exports = class SortOrderBehavior extends Base {
constructor (config) {
super({
orderAttr: 'orderNumber',
start: 10,
step: 10,
filter: null,
...config
});
this.setHandler(ActiveRecord.EVENT_BEFORE_INSERT, this.beforeInsert);
}
async beforeInsert () {
const order = this.owner.get(this.orderAttr);
if (CommonHelper.isEmpty(order)) {
const next = await this.getNextNumber();
this.owner.set(this.orderAttr, next);
}
}
async getNextNumber () {
const query = this.owner.find();
if (typeof this.filter === 'function') {
this.filter(query, this.owner);
} else if (typeof this.filter === 'string') {
const value = this.owner.get(this.filter);
query.and({[this.filter]: value});
}
const direction = this.step > 0 ? -1 : 1;
const order = {[this.orderAttr]: direction};
const last = await query.order(order).scalar(this.orderAttr);
return Number.isSafeInteger(last)
? last + this.step
: this.start;
}
async update (data) {
if (data) {
for (const id of Object.keys(data)) {
await this.updateById(id, data);
}
}
}
async updateById (id, data) {
const model = await this.owner.findById(id).one();
if (model) {
model.set(this.orderAttr, data[id]);
return model.update();
}
}
};
const CommonHelper = require('../helper/CommonHelper');
const ActiveRecord = require('../db/ActiveRecord');