Created
August 29, 2019 09:03
-
-
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
This file contains hidden or 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
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