Created
May 22, 2012 15:38
-
-
Save addisonj/2769817 to your computer and use it in GitHub Desktop.
a small wrapper for request that does fancy things
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
ServiceProxy = require "ServiceProxy" | |
module.exports = (service_host) -> | |
proxy1: (req, res) -> | |
# using a static method... | |
ServiceProxy.proxy req, res, { | |
host: service_host | |
onError: (err, req, res) -> | |
res.send err, 500 | |
transformUrl: (host, url) -> | |
# change the url as needed | |
return host + url.replace | |
} | |
#or create a class and define options | |
serviceProxy = new ServiceProxy { onError... } | |
proxy2: (req, res) -> | |
serviceProxy.proxy req, res |
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
request = require 'request' | |
_ = require 'underscore' | |
transformUrl = (host, url) -> | |
return host + url | |
onError = (err, req, res) -> | |
res.send "an error occurred", 500 | |
makeDefaults = (options) -> | |
options ?= {} | |
return { | |
transformUrl: options.transformUrl || transformUrl | |
onError: options.onError || onError | |
host: options.host || "http://localhost" | |
requestOpts: options.requestOpts || {} | |
} | |
buildRequestObject = (req, options) -> | |
{transformUrl, host, requestOpts} = options | |
requestOpts = _.extend requestOpts, { | |
url: transformUrl host, req.url | |
method: req.method.toLowerCase() | |
body: req.body | |
} | |
handleError = (pipe, onError, req, res) -> | |
pipe.on "error", (exception) -> | |
onError exception, req, res | |
proxy = (req, res, options) -> | |
options = makeDefaults options | |
requestOpts = buildRequestObject req, options | |
pipe = null | |
if requestOpts.method == "get" | |
pipe = request(requestOpts).pipe | |
else if requestOpts.method == "post" or requestOpts.method == "put" | |
pipe = req.pipe(request(requestOpts)).pipe | |
else | |
throw new Error "I don't support this HTTP method yet!" | |
handleError pipe, options.onError, req, res | |
pipe res | |
class ServiceProxy | |
constructor: (options) -> | |
# add the properties onto us | |
this = _.extend this, makeDefaults(options) | |
proxy: (req, res, options) -> | |
allOpts = _.extend this, options | |
proxy req, res, allOpts | |
ServiceProxy.proxy = proxy | |
module.exports = ServiceProxy |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment