1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('../base/Behavior');
|
7 |
|
8 | module.exports = class SortOrderBehavior extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | orderAttr: 'orderNumber',
|
13 | start: 10,
|
14 | step: 10,
|
15 | filter: null,
|
16 | ...config
|
17 | });
|
18 | this.setHandler(ActiveRecord.EVENT_BEFORE_INSERT, this.beforeInsert);
|
19 | }
|
20 |
|
21 | async beforeInsert () {
|
22 | if (CommonHelper.isEmpty(this.owner.get(this.orderAttr))) {
|
23 | this.owner.set(this.orderAttr, await this.getNextNumber());
|
24 | }
|
25 | }
|
26 |
|
27 | async getNextNumber () {
|
28 | const query = this.owner.find();
|
29 | if (typeof this.filter === 'function') {
|
30 | this.filter(query, this.owner);
|
31 | } else if (typeof this.filter === 'string') {
|
32 | query.and({[this.filter]: this.owner.get(this.filter)});
|
33 | }
|
34 | const last = await query.order({[this.orderAttr]: this.step > 0 ? -1 : 1}).scalar(this.orderAttr);
|
35 | return Number.isInteger(last) ? last + this.step : this.start;
|
36 | }
|
37 |
|
38 | async update (data) {
|
39 | if (data) {
|
40 | for (const id of Object.keys(data)) {
|
41 | await this.owner.findById(id).update({[this.orderAttr]: data[id]});
|
42 | }
|
43 | }
|
44 | }
|
45 | };
|
46 |
|
47 | const CommonHelper = require('../helper/CommonHelper');
|
48 | const ActiveRecord = require('../db/ActiveRecord'); |
\ | No newline at end of file |