Last active
April 20, 2016 02:15
-
-
Save icflorescu/5602592 to your computer and use it in GitHub Desktop.
Complex routing with express.js + CoffeeScript
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
### | |
It's incredibly easy to set-up a complex, SEO-friendly routing system using | |
the powerful CoffeeScript regular expressions and destructuring assignment syntax (to parse/name route parameters). | |
For instance, the code snippet below will respond to routes like: | |
/offers/category-automobiles | |
/offers/category-automobiles/make-alfa-romeo | |
/offers/category-automobiles/make-alfa-romeo/model-159 | |
/offers/year-min-2007 | |
/offers/year-max-2010 | |
/offers/make-alfa-romeo/year-min-2007-max-2012 | |
/offers/category-automobiles/make-alfa-romeo/model-159/transmission-manual | |
...etc. | |
### | |
# ... | |
searchRoutePattern = /// | |
^/offers | |
(?:/category-([^/]+))? # category | |
(?:/make-([^/]+))? # make | |
(?:/model-([^/]+))? # model | |
(?:/year | |
(?:-min-(\d{4}))? # yearMin | |
(?:-max-(\d{4}))? # yearMax | |
)? | |
(?:/km | |
(?:-min-(\d{1,6}))? # kmMin | |
(?:-max-(\d{1,6}))? # kmMax | |
)? | |
(?:/price | |
(?:-min-(\d{1,5}))? # priceMin | |
(?:-max-(\d{1,5}))? # priceMax | |
)? | |
(?:/transmission-(manual|automatic))? # transmission | |
(?:/drive-(fwd|rwd|4x4))? # drive | |
(?:/status-(new|second-hand))? # status | |
$ | |
/// | |
app.get searchRoutePattern, (req, res) -> | |
queryParams = {} | |
[ | |
queryParams.category | |
queryParams.make | |
queryParams.model | |
queryParams.yearMin | |
queryParams.yearMax | |
queryParams.kmMin, queryParams.kmMax | |
queryParams.priceMin, queryParams.priceMax | |
queryParams.transmission | |
queryParams.drive | |
queryParams.status | |
] = req.params | |
res.send queryParams # just show parsed params | |
# ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment