Skip to content

Instantly share code, notes, and snippets.

@addisonj
Created May 22, 2012 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save addisonj/2769817 to your computer and use it in GitHub Desktop.
Save addisonj/2769817 to your computer and use it in GitHub Desktop.
a small wrapper for request that does fancy things
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
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