Created
November 18, 2014 04:11
-
-
Save denkiryokuhatsuden/93093f78f5c1381cf3a3 to your computer and use it in GitHub Desktop.
[THIS DOES NOT WORK AT ALL] Simpler named routing feature 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
... | |
# before any routing requirings | |
require './router' | |
routes = require './routes/index' | |
... |
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
express = require('express') | |
router = express.Router() | |
router.route '/' | |
.bind 'index' | |
.get (req, res) -> | |
res.render 'index', { title: "named routing" } | |
router.route '/about/:what' | |
.bind 'about' | |
.get (req, res) -> | |
res.render 'about', { what: what } |
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
extends layout | |
block content | |
h1= title | |
ul | |
li | |
a(href=url('about', { what: 'me' })) about me | |
li | |
a(href=url('about', { what: 'company' })) about company |
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
### | |
inspired from https://github.com/silexphp/Silex | |
put this file onto your preferred place and just require. | |
### | |
express = require 'express' | |
routes = [] | |
### | |
bind() enables you to name the route | |
example | |
router.route '/' | |
.bind 'your-route-name' | |
.get blah-blah | |
.post blah-blah | |
### | |
express.Route.prototype.bind = (name) -> | |
console.log "#{@path} bound to #{name}" | |
routes[name] = @ | |
module.exports = (req, res, next) -> | |
### | |
helper url() enables you to generate url related to name that you once specified using bind() | |
### | |
res.locals.url = (name, param = {}) -> | |
route = routes[name] || { path: "##undefined route:#{name}" } | |
pattern = route.path | |
chunks = pattern.split '/' | |
requiredParams = [] | |
for c in chunks when c.charAt(0) == ':' then requiredParams.push c.slice 1 | |
for r in requiredParams | |
return "##parameter not satisfied: #{r}" unless r | |
p = param[r] | |
pattern = pattern.replace ":#{r}", p | |
req.baseUrl + pattern | |
next() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment