Skip to content

Instantly share code, notes, and snippets.

@dalgard
Last active September 14, 2015 07:30
Show Gist options
  • Save dalgard/3566bfbbe01443306a6f to your computer and use it in GitHub Desktop.
Save dalgard/3566bfbbe01443306a6f to your computer and use it in GitHub Desktop.
// Override the original behaviour from sewdn:collection-behaviours
CollectionBehaviours.defineBehaviour("trackable", function (getTransform, args) {
if (_.isArray(args[0]))
args = args[0];
// Track all updated fields or only a list of fields
if (args[0] === true) {
var track_field = args[1] || "updatedTrack",
slice = false;
if (_.isObject(track_field)) {
var prop_pair = _.pairs(track_field)[0];
track_field = prop_pair[0];
slice = prop_pair[1];
}
this.before.update(function (user_id, doc, field_names, modifier, options) {
var entry = {};
entry["userId"] = user_id;
entry["fields"] = _.pick(doc, field_names);
updateModifier(modifier, track_field, entry, slice);
});
}
else {
var fields = {};
_.each(args, function (field) {
if (_.isString(field))
fields[field] = null;
else if (_.isObject(field))
_.extend(fields, field);
});
this.before.update(function (user_id, doc, field_names, modifier, options) {
_.each(field_names, function (field_name) {
if (_.has(fields, field_name) && _.has(doc, field_name)) {
var entry = {},
slice = fields[field_name];
entry["userId"] = user_id;
entry[field_name] = doc[field_name];
updateModifier(modifier, field_name + "Track", entry, slice);
}
});
});
}
// Push the new entry onto modifier
function updateModifier(modifier, track_field_name, entry, slice) {
entry["trackedAt"] = new Date;
if (_.isFinite(slice))
entry = {
$each: [entry],
$slice: slice
};
if (!modifier.$push)
modifier.$push = {};
modifier.$push[track_field_name] = entry;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment