Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created June 4, 2012 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Raynos/2867867 to your computer and use it in GitHub Desktop.
Save Raynos/2867867 to your computer and use it in GitHub Desktop.
// Assume errorPage, jsonBody, formBody exist within scope.
function methods(routes, handleHttpForms) {
if (handleHttpForms) {
return createHttpFormsRequestHandler(routes)
}
return requestHandler
function requestHandler(req, res) {
var method = req.method,
f = routes[method]
if (f) {
return f.apply(this, arguments)
}
errorPage(req, res, 405)
}
}
function createHttpFormsRequestHandler(routes) {
return httpFormsRequestHandler
function httpFormsRequestHandler(req, res) {
if (req.method !== "POST") {
return requestHandler.apply(this, arguments)
}
var args = arguments,
self = this
contentTypes(req, {
"application/json": jsonBody,
"default": formBody
})(req, res, extractMethod)
function extractMethod(body) {
var method = body._method,
f = routes[method]
if (f) {
return f.apply(self, args)
}
errorPage(req, res, 405)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment