-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
54 lines (49 loc) · 1.79 KB
/
index.js
File metadata and controls
54 lines (49 loc) · 1.79 KB
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
const _ = require('lodash');
// Committed Plugin
// Emits the 'committed' event on `update` or `insert` when the save transaction completes for all models
// Note model.previousAttributes doesnt work with this.
module.exports = function(Bookshelf) {
const proto = Bookshelf.Model.prototype;
const Model = Bookshelf.Model.extend({
save: function(key, value, options) {
let attrs;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (key == null || typeof key === 'object') {
attrs = key || {};
options = _.clone(value) || {};
} else {
(attrs = {})[key] = value;
options = options ? _.clone(options) : {};
}
options.method = this.saveMethod(options);
const previousAttributes = _.clone(this.attributes) || {};
const save = proto.save.call(this, key, value, options);
if(options.method === 'insert' || options.method === 'update'){
if (options.transacting) {
options.transacting.__subscribers.push(() => {
this.triggerThen('committed', this.clone(), attrs, options, previousAttributes);
});
} else {
save.tap(model => model.triggerThen('committed', model.clone(), attrs, options, previousAttributes));
}
}
return save;
},
});
Bookshelf.transaction = function(originalContainer) {
const modelsToCommit = [];
let t;
const container = transactor => {
transactor.__subscribers = [];
t = transactor;
return originalContainer(transactor);
};
const args = Array.from(arguments);
const d = Bookshelf.knex.transaction.apply(this, [container, ...args.slice(1)])
d.then(() => {
t.__subscribers.forEach(subscriber => subscriber());
});
return d;
};
Bookshelf.Model = Model;
};