jack2
Version:
HTTP middleware for Node.js/Q-JSGI/JSGI2
71 lines (62 loc) • 1.99 kB
JavaScript
var Q = require("q");
var Q_HTTP = require("q-http");
var LOG_REQUEST_PROPS = ["method", "host", "port", "path", "headers"];
var LOG_RESPONSE_PROPS = ["status", "headers"];
function logProperties(string, object, properties) {
var items = [string];
properties.forEach(function(name) { items.push(name, object[name]) })
console.log.apply(console, items);
}
function Log(app) {
return function(request) {
logProperties("> ", request, LOG_REQUEST_PROPS);
delete request.url;
return Q.when(app(request), function(response) {
logProperties("< ", response, LOG_RESPONSE_PROPS);
return response;
});
}
}
var server = Q_HTTP.Server(Log(Cache(StripHopByHopHeaders(Q_HTTP.request))));
server.listen(4444);
function Cache(app) {
var cache = {};
return function(request) {
// if (request.path in cache) {
// return cache[request.path];
// } else {
return Q.when(app(request), function(response) {
var body = "";
return Q.when(response.body.forEach(function(chunk) {
body += chunk;
}), function() {
return cache[request.path] = {
status: response.status,
headers: response.headers,
body: [body]
};
});
});
// }
}
}
function StripHopByHopHeaders(app) {
return function(request) {
return Q.when(app(request), function(response) {
HOP_BY_HOP_HEADERS.forEach(function(header) {
delete response.headers[header];
});
return response;
});
}
}
var HOP_BY_HOP_HEADERS = [
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"TE",
"Trailers",
"Transfer-Encoding",
"Upgrade"
].map(function(header) { return header.toLowerCase(); });