Created
March 2, 2014 02:47
-
-
Save dburles/9301112 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var debug = function(str) { | |
console.log('counter-cache: ' + str); | |
}; | |
Meteor.Collection.prototype.maintainCountOf = function(collection, field, counterField) { | |
var self = this; | |
// what is Meteor.users an instanceof ? | |
// if (! (collection instanceof Meteor.Collection)) | |
// throw new Error("Expected first parameter to be a Meteor Collection"); | |
if (! collection) | |
throw new Error("Missing parameter: collection"); | |
if (! field) | |
throw new Error("Missing parameter: field name"); | |
if (typeof counterField === 'undefined') | |
counterField = self._name + 'Count'; | |
debug('setup counts of `' + collection._name + '` onto `' + this._name + '` with counter field `' + counterField + '`'); | |
var modifier = { $inc: {}}; | |
var decrement = function(_id) { | |
debug('decrement ' + _id); | |
if (! _id) return; | |
modifier[counterField] = 1; | |
self.update(_id, modifier); | |
}; | |
var increment = function(_id) { | |
debug('increment ' + _id); | |
if (! _id) return; | |
modifier[counterField] = -1; | |
self.update(_id, { $inc: { teachersCount: 1 }}); | |
}; | |
collection.after.insert(function(userId, doc) { | |
fieldValue = _.dottedProperty(doc, field); | |
if (fieldValue) | |
increment(fieldValue); | |
}); | |
collection.after.update(function(userId, doc, fieldNames, modifier, options) { | |
var self = this; | |
// console.log(modifier); | |
// console.log(fieldNames); | |
// console.log(this.previous); | |
// console.log(doc); | |
if (modifier.$set) { | |
var oldDoc = self.previous; | |
// LocalCollection._modify(doc, modifier); | |
var oldDocFieldValue = _.dottedProperty(oldDoc, field); | |
var newDocFieldValue = _.dottedProperty(doc, field); | |
if (oldDocFieldValue && newDocFieldValue !== oldDocFieldValue) | |
decrement(oldDocFieldValue); | |
increment(newDocFieldValue); | |
} | |
}); | |
collection.after.remove(function(userId, doc) { | |
decrement(_.dottedProperty(doc, field)); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment