Skip to content

Instantly share code, notes, and snippets.

@icflorescu
Last active April 20, 2016 02:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icflorescu/5602592 to your computer and use it in GitHub Desktop.
Save icflorescu/5602592 to your computer and use it in GitHub Desktop.
Complex routing with express.js + CoffeeScript
###
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