Skip to content

Instantly share code, notes, and snippets.

@gjohnson
Created October 29, 2013 13:47
Show Gist options
  • Save gjohnson/7214980 to your computer and use it in GitHub Desktop.
Save gjohnson/7214980 to your computer and use it in GitHub Desktop.
messing around
/**
* Module dependencies.
*/
var strftime = require('strftime');
/**
* Creates the `record` function for `collection`.
*
* Usage:
*
* ```
* var visits = db.collection('visit_stats');
* var record = mongostats(visits);
*
* record('www.example.com', {
* account: 'xxxx-xxxx-xxxx',
* }, callback);
* ```
*
* TODO:
*
* - make pre-allocations smarter so we dont
* waste send so many useless bytes over the wire.
*
* @param {Collection} collection
* @return {Function}
* @public
*/
module.exports = function (collection) {
return function record (name, meta, callback) {
if ('function' == typeof meta) {
callback = meta;
meta = null;
}
var inc = {};
var date = new Date();
var setOnInsert = prealloc(date, meta);
inc['total'] = 1;
inc[strftime('hour.%k', date)] = 1;
inc[strftime('minute.%k.%M', date)] = 1;
collection.update({
query: {
_id: strftime('%Y-%M-%d_' + name)
},
update: {
$setOnInsert: setOnInsert,
$inc: inc
},
upsert: true
}, callback || noop);
};
}
/**
* Document pre-allocation.
*
* @param {Date} date
* @param {Object|Null} meta
* @return {Object}
* @private
*/
function prealloc (date, meta) {
var stats = {
meta: meta || {}
minute: {},
hour: {},
total: 0,
};
range(0, 24, set(stats.hour, 0));
range(0, 60, set(stats.minute, 0));
return stats;
}
/**
* Naive sequence.
*
* @param {Number} start
* @param {Number} stop
* @param {Function} fn
* @private
*/
function range (start, stop, fn) {
for (var i = start; i < stop; ++i) fn(i);
}
/**
* Assignment utility.
*
* @param {Object} object
* @param {Mixed} value
* @return {Function}
* @private
*/
function set (object, value) {
return function (key) {
object[key] = value;
};
}
/**
* Noop.
*
* @private
*/
function noop () {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment