Rails-like routing for Express 3.x
高仿 Rails 路由的几个常用方法,支持 namespace,支持(链式)多级嵌套,支持 before_filter 和 skip_before_filter。欢迎 Pull Requests。
Installation
$ npm install railstyle-router
Usage
var express = var app = app appapp
./controllers/users_controller.js
:
// GET /usersexports { console console console res} // GET /users/newexports { res} // POST /usersexports { res} // GET /users/:idexports { res} // GET /users/:id/editexports { res} // PUT /users/:idexports { res} // DELETE /users/:idexports { res}
APIs
.resources(name, [options])
默认绑定 index
, show
, new
, edit
, create
, update
, destroy
七个 actions。
options
支持:
path
: 重写 URL 路径,不设置则默认同name
一致only
: 指定需要保留的 actions,可以传入数组,亦可传入以逗号分隔的字符串。如果想排除所有的 actions,请传入空数组[]
,而非空字符串或其他except
: 排除指定的 actions,可以传入数组,亦可传入以逗号分隔的字符串
举个栗子🌰:
app.resources GET /users.:format? users#indexGET /users/:id.:format? users#showGET /users/new.:format? users#newGET /users/:id/edit.:format? users#editPOST /users.:format? users#createPUT /users/:id.:format? users#updateDELETE /users/:id.:format? users#destroy
app.resources GET /person/:id.:format? users#showGET /person/new.:format? users#newPOST /person.:format? users#create
.resource(name, [options])
默认绑定 show
, new
, edit
, create
, update
, destroy
六个 actions。
options
同 resources
。
举个🌰:
app.resource GET /users.:format? users#showGET /users/new.:format? users#newGET /users/edit.:format? users#editPOST /users.:format? users#createPUT /users.:format? users#updateDELETE /users.:format? users#destroy
.member(routes) / .collection(routes)
这两个方法用于创建非 RESTful 的路由,配合 resources
和 resource
使用:
app.resources
app.resources
回调君还能协助实现嵌套路由,上🌰:
app.resources
不喜欢回调回调再回调?试试链式的:
app.resources
.match(path, [namespace/]controller#action, [via])
使某个 controller 下的 action 与指定的路径匹配,如果这个 action 属于 .resources()
默认 actions 的其中之一,则只会匹配相对应的 HTTP method。via
默认同时包括 get
, post
, put
, delete
四个 HTTP methods,使用该参数可以覆盖 RESTful 规则。
app.match GET /login.:format? sessions#new
app.match POST /login.:format? sessions#create
app.match GET|POST|PUT|DELETE /login.:format? sessions#ooxx
app.match GET|POST /login.:format? sessions#ooxx
.namespace(path, callback)
app.namespace
同样支持链式:
app.namespace.resources
before_filter
在 controller 文件中加上如下代码即可。action 跟 middleware 可以一对一、一对多、多对一、多对多。星号 *
匹配所有 actions,且优先级最高。
exportsbefore_filter = '*': fn1 'create, update': fn2 'create': fn3 fn4 'destroy': fn4 { //... } { //... } { //... } { //... }
ApplicationController
星号 *
只能匹配当前 controller,想要在全部 controller 中生效,则需要使用 application[suffix].js
,优先级比星号 *
更高:
moduleexports = { // global filter middleware} exports { //... }
skip_before_filter
在需要 skip 某些中间件的 controller 里:
exportsskip_before_filter = 'new': true // skip everything 'create, update': '-g' fn1 // `-g` 指 `application[suffix].js` 的 `module.exports` 'destroy': fn2 fn3 // skip 具体的中间件
License
Licensed under the MIT License.