counter-cache.js
5.22 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
'use strict';
var Utils = require('./../utils')
, Helpers = require('../associations/helpers')
, DataTypes = require('../data-types')
, Promise = require('bluebird');
var CounterCache = function(association, options) {
this.association = association;
this.source = association.source;
this.target = association.target;
this.options = options || {};
this.sequelize = this.source.modelManager.sequelize;
this.as = this.options.as;
if (association.associationType !== 'HasMany') {
throw new Error('Can only have CounterCache on HasMany association');
}
if (this.as) {
this.isAliased = true;
this.columnName = this.as;
} else {
this.as = 'count_' + this.target.options.name.plural;
this.columnName = Utils.camelizeIf(
this.as,
!this.source.options.underscored
);
}
this.injectAttributes();
this.injectHooks();
};
// Add countAssociation attribute to source model
CounterCache.prototype.injectAttributes = function() {
// Do not try to use a column that's already taken
Helpers.checkNamingCollision(this);
var newAttributes = {};
newAttributes[this.columnName] = {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: Utils._.partial(
Utils.toDefaultValue,
0
)
};
Utils.mergeDefaults(this.source.rawAttributes, newAttributes);
// Sync attributes and setters/getters to DAO prototype
this.source.refreshAttributes();
};
// Add setAssociaton method to the prototype of the model instance
CounterCache.prototype.injectHooks = function() {
var association = this.association,
counterCacheInstance = this,
CounterUtil,
fullUpdateHook,
atomicHooks,
previousTargetId;
CounterUtil = {
update: function (targetId, options) {
var query = CounterUtil._targetQuery(targetId);
return association.target.count({ where: query, logging: options && options.logging }).then(function (count) {
var newValues = {};
query = CounterUtil._sourceQuery(targetId);
newValues[counterCacheInstance.columnName] = count;
return association.source.update(newValues, { where: query, logging: options && options.logging });
});
},
increment: function (targetId, options) {
var query = CounterUtil._sourceQuery(targetId);
return association.source.find({ where: query, logging: options && options.logging }).then(function (instance) {
return instance.increment(counterCacheInstance.columnName, { by: 1, logging: options && options.logging });
});
},
decrement: function (targetId, options) {
var query = CounterUtil._sourceQuery(targetId);
return association.source.find({ where: query, logging: options && options.logging }).then(function (instance) {
return instance.decrement(counterCacheInstance.columnName, { by: 1, logging: options && options.logging });
});
},
// helpers
_targetQuery: function (id) {
var query = {};
query[association.foreignKey] = id;
return query;
},
_sourceQuery: function (id) {
var query = {};
query[association.source.primaryKeyAttribute] = id;
return query;
}
};
fullUpdateHook = function (target, options) {
var targetId = target.get(association.foreignKey)
, promises = [];
if (targetId) {
promises.push(CounterUtil.update(targetId, options));
}
if (previousTargetId && previousTargetId !== targetId) {
promises.push(CounterUtil.update(previousTargetId, options));
}
return Promise.all(promises).return(undefined);
};
atomicHooks = {
create: function (target, options) {
var targetId = target.get(association.foreignKey);
if (targetId) {
return CounterUtil.increment(targetId, options);
}
},
update: function (target, options) {
var targetId = target.get(association.foreignKey)
, promises = [];
if (targetId && !previousTargetId) {
promises.push(CounterUtil.increment(targetId, options));
}
if (!targetId && previousTargetId) {
promises.push(CounterUtil.decrement(targetId, options));
}
if (previousTargetId && targetId && previousTargetId !== targetId) {
promises.push(CounterUtil.increment(targetId, options));
promises.push(CounterUtil.decrement(previousTargetId, options));
}
return Promise.all(promises);
},
destroy: function (target, options) {
var targetId = target.get(association.foreignKey);
if (targetId) {
return CounterUtil.decrement(targetId, options);
}
}
};
// previousDataValues are cleared before afterUpdate, so we need to save this here
association.target.addHook('beforeUpdate', function (target) {
previousTargetId = target.previous(association.foreignKey);
});
if (this.options.atomic === false) {
association.target.addHook('afterCreate', fullUpdateHook);
association.target.addHook('afterUpdate', fullUpdateHook);
association.target.addHook('afterDestroy', fullUpdateHook);
} else {
association.target.addHook('afterCreate', atomicHooks.create);
association.target.addHook('afterUpdate', atomicHooks.update);
association.target.addHook('afterDestroy', atomicHooks.destroy);
}
};
module.exports = CounterCache;