Created
January 7, 2014 13:24
-
-
Save yanneves/8299215 to your computer and use it in GitHub Desktop.
StackMob Node Proxy
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
// proxy all API requests | |
function proxy(method, path, headers, data) { | |
var defer = q.defer(), request, | |
pubKey = '****'; | |
// filter paramaters contained in header, to avoid | |
// incorrectly identifying client domain and agent in request | |
headers = _.pick(headers, ['x-stackmob-api-key', 'x-stackmob-proxy-plain', 'x-stackmob-api-key-' + pubKey, 'accept', 'content-type', 'content-length', 'authorization']); | |
// format headers | |
headers = { | |
'X-StackMob-API-Key': headers['x-stackmob-api-key'], | |
'X-StackMob-Proxy-Plain': headers['x-stackmob-proxy-plain'], | |
'Accept': headers.accept, | |
'Content-Type': headers['content-type'] || 'application/json', | |
'Authorization': headers.authorization | |
}; headers['X-StackMob-API-Key' + pubKey] = pubKey; | |
// add content-length buffer to header, if data exists | |
if (data) headers['Content-Length'] = Buffer.byteLength(data); | |
// create request | |
request = http.request({ | |
host: 'api.stackmob.com', | |
port: 80, | |
path: path, | |
method: method, | |
headers: headers | |
}, function(res) { defer.resolve(res);}); | |
// append data to request, if exists | |
if (data) request.write(data); | |
// close request | |
request.end(); | |
// return promise | |
return defer.promise; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment