Skip to content

Commit

Permalink
Adding argument hashing
Browse files Browse the repository at this point in the history
  • Loading branch information
tmuellerleile committed Feb 15, 2012
1 parent 7bc0818 commit b6c6131
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Memoize asynchronous function calls using memcached
mmemoize = require('mmemoize');

var memcached = new Memcached('localhost:11211'),
mmemoizer = mmemoize(memcached, { ttl: 120 }); // in seconds
mmemoizer = mmemoize(memcached /*, config */);

var a = function (/* someArguments, */ callback) {
// some potentially expensive computations, database fetches etc.
Expand All @@ -24,6 +24,13 @@ Memoize asynchronous function calls using memcached
// just in case:
a = a.dememoize(); // or: a = mmemoizer.dememoize(a);

## Configuration

Send config object as the second parameter of mmemoize(), use the following options:

- `ttl`: Key TTL in seconds; default: `120`
- `hashAlgorithm`: Algorithm used for hashing function arguments in memcached keys, set to `null` for no hashing at all, for possible values see [node.js' crypto documentation](http://nodejs.org/docs/latest/api/crypto.html#crypto.createHash); default: `sha1`

## Deployment dependencies
- [node-memcached](https://github.com/3rd-Eden/node-memcached) (of course)

Expand Down
28 changes: 25 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
var mmemoize = function (memcached, config) {
var crypto = require('crypto');

var that = {};

var configDefaults = {
ttl: 120
ttl: 120,
hashAlgorithm: 'sha1'
};
var that = {};
var cProp;
for (cProp in configDefaults) {
if (configDefaults.hasOwnProperty(cProp) && config[cProp] === undefined) {
Expand All @@ -21,7 +25,7 @@ var mmemoize = function (memcached, config) {
if (typeof args.slice(-1).pop() === 'function') {
fctCallback = args.pop(); // cache and remove original callback
}
key = keyPrefix + ':' + JSON.stringify(args);
key = calcKey(keyPrefix, args);
memcached.get(key, function (err, mcdResult) {
if (err !== undefined || mcdResult === undefined || mcdResult === false) { // memcache error or miss:
args.push(function () { // register our new callback:
Expand Down Expand Up @@ -59,6 +63,24 @@ var mmemoize = function (memcached, config) {
};
that.dememoize = dememoize;

// PRIVATE METHODS:
var calcKey = function (prefix, args) {
var key,
hasher;
if (typeof args !== 'string') {
args = JSON.stringify(args);
}
if (config.hashAlgorithm !== null) { // hash arguments:
hasher = crypto.createHash(config.hashAlgorithm);
hasher.update(args);
key = prefix + ':' + hasher.digest('hex');
}
else {
key = prefix + ':' + args;
}
return key;
};

return that;
};
module.exports = mmemoize;

0 comments on commit b6c6131

Please sign in to comment.