Skip to content

Instantly share code, notes, and snippets.

@treasonx
Created January 2, 2013 23:33
Show Gist options
  • Save treasonx/4439383 to your computer and use it in GitHub Desktop.
Save treasonx/4439383 to your computer and use it in GitHub Desktop.
Meld Aspects
var when = require('when');
var meld = require('meld');
var winston = require('winston');
var config = require('./config');
var dbAspects = {
introDeferred: function(obj,name) {
meld.around(obj, name, function(joinpoint) {
var def = when.defer();
var promise = def.promise;
var client = joinpoint.args[0];
client.query('BEGIN');
promise.then(function() {
client.query('COMMIT');
}, function() {
client.query('ROLLBACK');
});
promise.always(client.release);
joinpoint.args.unshift(def);
joinpoint.proceed();
return promise;
});
},
introRollbackDeferred: function(obj,name) {
meld.around(obj, name, function(joinpoint) {
var def = when.defer();
var promise = def.promise;
var client = joinpoint.args[0];
client.query('BEGIN');
promise.always(function() {
client.query('ROLLBACK');
client.release();
});
joinpoint.args.unshift(def);
joinpoint.proceed();
return promise;
});
},
introduceDeferred: function(obj, name) {
meld.around(obj, name, function(joinpoint) {
var def = when.defer();
var promise = def.promise;
joinpoint.args.push(function(err, result) {
if(err) {
def.reject(err);
} else {
def.resolve(result);
}
});
joinpoint.proceed();
return promise;
});
}
};
var ke$ha = {
tikTok: function(tag, obj, name) {
meld.around(obj, name, function(joinpoint) {
var start, result;
if(!config.tikTok) {
joinpoint.proceed();
} else {
start = new Date.getTime();
result = null;
joinpoint.proceed();
if(start) {
result = new Date.getTime() - start;
winston.log(tag+' '+result);
}
}
});
}
};
@briancavalier
Copy link

These are great--simple, but effective.

Only one suggestion: it's probably better not to modify joinpoint.args directly. You can pass new args to either joinpoint.proceed() or joinpoint.proceedApply(). For example, instead of:

joinpoint.args.unshift(def);
joinpoint.proceed();

you can do:

joinpoint.proceedApply([def].concat(joinpoint.args));

Now you have me wondering about whether modifying joinpoint.args directly would ever cause a problem :) I better go check teh codez!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment