Created
January 15, 2014 23:54
-
-
Save mndvns/8447177 to your computer and use it in GitHub Desktop.
app.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Module dependencies | |
*/ | |
var stack = require('simple-stack-ui'); | |
var envs = require('envs'); | |
var qs = require('qs'); | |
var app = module.exports = stack({ | |
restricted: false | |
}); | |
app.locals({ | |
title: 'Advanced Reports' | |
}); | |
/** | |
* Setup app-wide locals | |
*/ | |
app.env('API_URL', '/api'); | |
/** | |
* Hackity hack for rewriting header. | |
*/ | |
var base_idx = app.indexOf('base'); | |
var api_idx = app.indexOf('api-proxy'); | |
app.stack.splice(api_idx, 0, app.stack.splice(base_idx, 1)[0]); | |
app.useBefore('api-proxy', '/api', 'api-cookies', stack.middleware.cookieParser()); | |
var apiUrl = new RegExp(envs('API_URL'), 'g'); | |
app.useBefore('api-proxy', '/api', 'proxy-rewrite', function(req, res, next) { | |
var buf = []; | |
var write = res.write; | |
var end = res.end; | |
var writeHead = res.writeHead; | |
req.cookies._access_token = envs('ACCESS_TOKEN'); | |
if (req.cookies._access_token) req.headers.authorization = 'Bearer ' + req.cookies._access_token; | |
res.set('cache-control', 'max-age=3600'); | |
res.writeHead = function(code, headers) { | |
if (headers) delete headers['content-length']; | |
writeHead.apply(this, arguments); | |
}; | |
res.end = function(data, encoding, cb) { | |
if (data) buf.push(data.toString()); | |
var newData = buf.join('').replace(apiUrl, req.base + '/api'); | |
newData = newData.replace(/data\/(give|receive|utilization|reach)"/g, function(match, type) { | |
return 'data/' + type + '?' + qs.stringify(req.query) + '"'; | |
}).replace(/(beginDate|endDate)\":{\"type\":\"hidden\",/g, function(match, type) { | |
return type + '":{'; | |
}); | |
end.apply(this, [newData, encoding, cb]); | |
}; | |
res.write = function(data, encoding, cb) { | |
buf.push(data.toString()); | |
write.apply(this, ['', encoding, cb]); | |
}; | |
next(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment