Skip to content

Instantly share code, notes, and snippets.

@shesek
Last active December 14, 2015 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shesek/5122225 to your computer and use it in GitHub Desktop.
Save shesek/5122225 to your computer and use it in GitHub Desktop.
Express sub routes
express = require 'express'
express().configure ->
subroute.install this # or subroute.install() to install globally
@subroute '/a', -> # or `subroute app, '/a', ->` without `install()`ing
@use (req, res, next) -> # ...
@get (req, res, next) -> # ...
@get '/test', (req, res, next) -> # ...
@subroute '/b', ->
@use (req, res, next) -> # ...
@get (req, res, next) -> # ...
@post (req, res, next) -> # ...
# also passes a parameter, which can be used if `this` is needed
@subroute '/c', (route) =>
route.get # ...
###
## MOVED TO https://github.com/shesek/express-subroute
###
methods = require 'methods'
curryThis = (fn) -> (a...) -> fn this, a...
isString = (o) -> (Object::toString.call o) is '[object String]'
path_methods = [ methods..., 'use', 'all' ]
wrap = (fn, path) -> (spath, a...) ->
if isString spath then fn.call this, path+spath, a...
else fn.call this, path, spath, a...
subroute = (app, path, fn) ->
sapp = Object.create app
sapp[method] = wrap app[method], path for method in path_methods
fn.call sapp, sapp
subroute.install = (app = (require 'express').application) -> app.subroute = curryThis subroute
module.exports = subroute
{"name": "express-subroute", "version": "0.0.1", "main": "express-subroute.coffee", "dependencies": { "methods": "*" }, "license": "WTFPL"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment