Last active
December 10, 2015 17:58
-
-
Save maxatwork/4470855 to your computer and use it in GitHub Desktop.
RoR-style REST routes for express.
This file contains 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
# Returns function which adds RESTful routes to express.js application | |
# for specified controller | |
# | |
# Usage: | |
# resource = resourceRoutesBuilder(app) | |
# resource 'person', person | |
# | |
# This will map routes to: | |
# | |
# GET '/persons/new' -> person.new(req, res) # shows form for new person creation | |
# POST '/persons/ -> person.create(req, res) # actually creates new person | |
# GET '/persons/' -> person.index(req, res) # shows list of all persons | |
# GET '/persons/:personId -> person.show(req, res) # shows specified person details | |
# GET '/persons/:personId/edit' -> person.edit(req, res') # shows person edit form | |
# PUT '/persons/:personId' -> person.update(req, res) # actually updates specified person | |
# DELETE '/persons/:personId' -> person.delete(req, res) # deletes specified person | |
resourceRoutesBuilder = (app) -> (base, resource, controller) -> | |
[base, resource, controller] = ['', base, resource] unless controller? | |
plural = "#{resource}s" | |
plural = "#{resource.substr(0, resource.length - 1)}ies" if (/y$/i).test resource | |
app.get "#{base}/#{plural}/new", controller.new if controller.new? | |
app.post "#{base}/#{plural}/", controller.create if controller.create? | |
app.get "#{base}/#{plural}/", controller.index if controller.index? | |
app.get "#{base}/#{plural}/:#{resource}Id", controller.show if controller.show? | |
app.get "#{base}/#{plural}/:#{resource}Id/edit", controller.edit if controller.edit? | |
app.put "#{base}/#{plural}/:#{resource}Id", controller.update if controller.update? | |
app.delete "#{base}/#{plural}/:#{resource}Id", controller.delete if controller.delete? | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment