Alex
Alex

Reputation: 11147

setting a before/after hook for methods in node.js

How can i set a before/after "hook" for methods in node.js?

i need it to execute certain actions before certain method is called. I'm using node.js 10.36 with socket.io 1.2.

Upvotes: 0

Views: 2972

Answers (1)

Telokis
Telokis

Reputation: 3389

Extending Function:

Here is a little extension to Function.Prototype

Function.prototype.before = function (callback) {
    var that = this;
    return (function() {
        callback.apply(this, arguments);
        return (that.apply(this, arguments));
    });
}

Function.prototype.after = function (callback) {
    var that = this;
    return (function() {
        var result = that.apply(this, arguments);
        callback.apply(this, arguments);
        return (result);
    });
}

These two extensions return the function to call.

Here is a little example:

function test(a) {
    console.log('In test function ! a = ', a);
}
test(15); // "In test function ! a =  15"

With before:

var beforeUsed = test.before(function(a) {
    console.log('Before. Parameter = ', a);
});
beforeUsed(65); // "Before. Parameter =  65"
                // "In test function ! a =  65"

With after:

var afterUsed = beforeUsed.after(function(a) {
    console.log('After. Parameter = ', a);
});
afterUsed(17); // "Before. Parameter =  17"
               // "In test function ! a =  17"
               // "After. Parameter =  17"

You also can chain:

var both = test.before(function(a) {
    console.log('Before. Parameter = ', a);
}).after(function(a) {
    console.log('After. Parameter = ', a);
});
both(17); // Prints as above

Upvotes: 3

Related Questions