Skip to content

Instantly share code, notes, and snippets.

@Xetera
Created August 29, 2019 09:03
Show Gist options
  • Save Xetera/ee8dafcfbffe036af9c219fe4feefbf5 to your computer and use it in GitHub Desktop.
Save Xetera/ee8dafcfbffe036af9c219fe4feefbf5 to your computer and use it in GitHub Desktop.
A helper function that lets you declare multiple methods for the same endpoint in express.js without repeating things
const routeMethods = (router, url) => {
const unwrap = () => router
const makeRoute = method => handler => {
router[method](url, handler);
return routeMethods(router, url)
}
const methods = ['get', 'post', 'put', 'options', 'delete', 'patch', /* as many methods as you need here */]
return methods.reduce((all, method) => ({
...all,
[method]: makeRoute(method)
}), { unwrap })
}
export const dabRouter = routeMethods(new Router(), "/dab/:id")
.get((req, res) => res.json({ yeet: 1 }))
.put((req, res) => res.send(`${req.params.id}, you put 1 dab`))
.post(() => {})
.unwrap()
// you have to call `unwrap` at the end if you want to return the modified router object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment