Skip to content

Instantly share code, notes, and snippets.

@johnkors
Created June 14, 2012 10:28
Show Gist options
  • Save johnkors/2929481 to your computer and use it in GitHub Desktop.
Save johnkors/2929481 to your computer and use it in GitHub Desktop.
"Overloads" in javascript
// http://howtonode.org/connect-it
// 1: store original
// 2: overwrite existing method with new function with extra functionality
// 3: in new function from 2, call the original method stored in 1.
module.exports = function logItSetup() {
// Initialize the counter
var counter = 0;
return function logItHandle(req, res, next) {
var writeHead = res.writeHead; // 1. Store the original function
counter++;
// Log the incoming request
console.log("Request " + counter + " " + req.method + " " + req.url);
// 2. Wrap writeHead to hook into the exit path through the layers.
res.writeHead = function (code, headers) {
res.writeHead = writeHead; // Put the original back
// Log the outgoing response
console.log("Response " + counter + " " + code + " " + JSON.stringify(headers));
res.writeHead(code, headers); // 3. Call the original
};
// Pass through to the next layer
next();
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment