Skip to content

Instantly share code, notes, and snippets.

@lookingcloudy
Created December 31, 2013 13:30
Show Gist options
  • Save lookingcloudy/8196828 to your computer and use it in GitHub Desktop.
Save lookingcloudy/8196828 to your computer and use it in GitHub Desktop.
nodejs server side proxy example using restify, showing a proxy to smarty streets address service
// NODE.JS - SMARTY STREETS SERVER SIDE PROXY EXAMPLE
//
// Smarty streets does not currently support HTTP OPTIONS. Because of this,
// if setting custom headers, it cannot be called from a browser-side library
// like AngularJS.
//
// This is a server side proxy for smarty-streets. It takes the request
// query string and passes it on to Smarty Streets along with any of the
// custom headers that Smarty Streets currently supports.
//
// This sample code only depends on the external restify library. It is a
// sample pattern for proxying any request using restify and redirecting to
// another service.
var restify = require('restify');
var querystring = require('querystring');
var https = require('https');
var http = require('http');
var url = require('url');
var port = '8080';
var server = restify.createServer({
name: "ProxyService"
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.gzipResponse());
server.pre(restify.pre.userAgentConnection());
// Generic request function
// host, endpoint, method, data, headers, success) {
function proxyRequest(req, res, proxyOptions) {
var options = {};
options.host = proxyOptions.host;
options.path = proxyOptions.endpoint + '?' + querystring.stringify(proxyOptions.query);
options.method = proxyOptions.method;
options.headers = proxyOptions.headers;
console.log("URL: ", options.host+options.path);
// determine whether to use https
//
if (proxyOptions.https) {
var protocol = https
}else{
var protocol = http
};
var req = protocol.request(options, function(res) {
var responseString = '';
res.on('data', function(data) {
responseString += data;
});
res.on('end', function() {
proxyOptions.callback(responseString);
});
req.on('error', function(e) {
console.error(e);
});
});
req.end();
};
server.get('/street-address', function respond(req, res, next){
var auth = {'auth-Id': 'insert authstring here',
'auth-token': 'insert auth token here'};
var testData = {'street': '1600 Amphitheatre Parkway','street2': '','city': 'Mountain View','state': 'CA','zipcode': '','candidates': 10};
var extraHeaders = { 'Content-Type': 'application/json' };
var options = {
host: 'api.smartystreets.com',
method: 'GET',
endpoint: '/street-address',
query: {},
https: true,
headers: {},
callback: function() {}
};
// add the authcode
options.query = auth;
// add testdata to query string if empty
if (!url.parse(req.url, true).query.street) {
// add the test data string
options.query = collect(options.query, testData);
};
//add extra headers
options.headers = extraHeaders;
//look for custom smarty streets headers in the request
var copyHeaders = ['x-standardize-only', 'x-include-invalid', 'Accept', 'x-accept-keypair', 'x-suppress-logging'], hdr;
for (var i=0; i<copyHeaders.length; i++ ) {
hdr = copyHeaders[i];
if (req.headers.hasOwnProperty(hdr)) {
options.headers[hdr] = req.headers[hdr];
}
}
// set the call back functionality
options.callback = function(responseData) {
res.send( JSON.parse(responseData) );
res.end();
return next();
};
// proxy the request to smartystreets using https
proxyRequest(req, res, options);
});
//
// COLLECT - object concat
//
function collect(ob1, ob1) {
var ret = {},
len = arguments.length,
arg,
i = 0,
p;
for (i = 0; i < len; i++) {
arg = arguments[i];
if (typeof arg !== "object") {
continue;
}
for (p in arg) {
if (arg.hasOwnProperty(p)) {
ret[p] = arg[p];
}
}
}
return ret;
};
server.listen(port, function(){
console.log("===========================================================================");
console.log('%s listening at %s ', server.name , server.url);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment