Skip to content

Instantly share code, notes, and snippets.

@ralt
Forked from Raynos/methods.js
Created June 4, 2012 12:32
Show Gist options
  • Save ralt/2868086 to your computer and use it in GitHub Desktop.
Save ralt/2868086 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.bind(this)
}
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