express4-resource
v1.1.0
Published
Resourceful routing for express4
Downloads
3
Maintainers
Readme
Express4 Resourceful Routing
express4-resource provides resourceful routing to express.
Installation
$ npm install express4-resource
Usage
app.js
// things are included up here
require('express-resource')(app);
require('./router')(app, passport);
router/index.js
module.exports = function(app) {
app.resource('api/objects', require('../controllers/object'));
};
controllers/object.js
module.exports = {
index: = function(req, res){
// GET /api/objects
// Display a listing of the resource.
res.send('list objects');
},
new: function(req, res){
// GET /api/objects/new
// Show the form for creating a new resource.
res.send('show new object form');
},
create: function(req, res){
// POST /api/objects
// Store a newly created resource in storage.
res.send('create object');
},
show: function(req, res){
// GET /api/objects/:id
// Display the specified resource.
res.send('show forum ' + req.params.object);
},
edit: function(req, res){
// GET /api/objects/edit/:id
// Show the form for editing the specified resource.
res.send('edit forum ' + req.params.object);
},
update: function(req, res){
// PUT /api/objects/:id
// Update the specified resource in storage.
res.send('update forum ' + req.params.object);
},
patch: function(req, res){
// PATCH /api/objects/:id
res.send('update forum ' + req.params.object);
},
destroy: function(req, res){
// DELETE /api/objects/:id
// Remove the specified resource from storage.
res.send('destroy forum ' + req.params.object);
}
};
Default Action Mapping
Actions are then mapped as follows (by default), providing req.params.object
which contains the substring where ":object" is shown below:
GET /objects -> index
GET /objects/new -> new
POST /objects -> create
GET /objects/:object -> show
GET /objects/:object/edit -> edit
PUT /objects/:object -> update
PATCH /objects/:object -> patch
DELETE /objects/:object -> destroy
Top-Level Resource
Specify a top-level resource by omitting the resource name:
app.resource(require('./forum'));
Top-level actions are then mapped as follows (by default):
GET / -> index
GET /new -> new
POST / -> create
GET /:id -> show
GET /:id/edit -> edit
PUT /:id -> update
PATCH /:id -> patch
DELETE /:id -> destroy
Auto-Loading
Resources have the concept of "auto-loading" associated data. For example we can pass a "load" property along with our actions, which should invoke the callback function with an error, or the object such as a User
:
User.load = function(id, fn) {
fn(null, users[id]);
};
// or
User.load = function(req, id, fn) {
fn(null, users[id]);
};
app.resource('users', { show: ..., load: User.load });
With the auto-loader defined, the req.user
object will be available now be available to the actions automatically. We may pass the "load" option as the third param as well, although this is equivalent to above, but allows you to either export ".load" along with your actions, or passing it explicitly:
app.resource('users', require('./user'), { load: User.load });
Finally we can utilize the Resource#load(fn)
method, which again is functionally equivalent:
var user = app.resource('users', require('./user'));
user.load(User.load);
This functionality works when nesting resources as well, for example suppose we have a forum, which contains threads, our setup may look something like below:
var forums = app.resource('forums', require('resources/forums'), { load: Forum.get });
var threads = app.resource('threads', require('resources/threads'), { load: Thread.get });
forums.add(threads);
Now when we request GET /forums/5/threads/12
both the req.forum
object, and req.thread
will be available to thread's show action.
Content-Negotiation
Currently express-resource supports basic content-negotiation support utilizing extnames or "formats". This can currently be done two ways, first we may define actions as we normally would, and utilize the req.format
property, and respond accordingly. The following would respond to GET /pets.xml
, and GET /pets.json
.
var pets = ['tobi', 'jane', 'loki'];
exports.index = function(req, res){
switch (req.format) {
case 'json':
res.send(pets);
break;
case 'xml':
res.send('<pets>' + pets.map(function(pet){
return '<pet>' + pet + '</pet>';
}).join('') + '</pets>');
break;
default:
res.send(406);
}
};
The following is equivalent, however we separate the logic into several callbacks, each representing a format.
exports.index = {
json: function(req, res){
res.send(pets);
},
xml: function(req, res){
res.send('<pets>' + pets.map(function(pet){
return '<pet>' + pet + '</pet>';
}).join('') + '</pets>');
}
};
We may also provide a default
format, invoked when either no extension is given, or one that does not match another method is given:
exports.default = function(req, res){
res.send('Unsupported format "' + req.format + '"', 406);
};
To assign a default format to an existing method, we can provide the format
option to the resource. With the following definition both GET /users/5
and GET /users/5.json
will invoke the show.json
action, or show
with req.format = 'json'
.
app.resource('users', actions, { format: 'json' });
Middleware
This version supports attaching route middleware to actions.
Every action can have its own different middleware attached (or no middleware at all).
The middleware can be specified in one of two ways: by passing a middleware
option to app.resource()
or by attaching it directly to the actions.
middleware option
With the middleware
option, it's possible to specify the middleware in a single place:
var forumsMiddleware = {
index: authMiddleware,
new: [authMiddleware, adminMiddleware],
create: [authMiddleware, adminMiddleware],
show: authMiddleware,
edit: [authMiddleware, adminMiddleware],
update: [authMiddleware, adminMiddleware],
patch: [authMiddleware],
destroy: [authMiddleware, adminMiddleware]
};
app.resource('forums', require('./forum'), {middleware: forumsMiddleware});
It's also possible to specify a special "glob" key, that matches every action, and is considered when no specific middleware is specified:
var forumsMiddleware = {
'*': authMiddleware,
new: [authMiddleware, adminMiddleware],
create: [authMiddleware, adminMiddleware],
edit: [authMiddleware, adminMiddleware],
update: [authMiddleware, adminMiddleware],
destroy: [authMiddleware, adminMiddleware]
};
app.resource('forums', require('./forum'), {middleware: forumsMiddleware});
inline middleware
It's also possible to specify the route middleware directly with the actions. There are two styles, with a JavaScript object or with an array:
exports.index = {
middleware: authMiddleware,
fn: function(req, res){
res.send('forum index');
}
};
exports.new = [ authMiddleware, adminMiddleware, function(req, res){
res.send('new forum');
} ];
exports.create = {
middleware: [ authMiddleware, adminMiddleware ],
fn: function(req, res){
res.send('create forum');
}
};
Running Tests
First make sure you have the submodules:
$ git submodule update --init
Then run the tests:
$ make test
License
The MIT License
Copyright (c) 2010-2014 TJ Holowaychuk <[email protected]>
Copyright (c) 2011 Daniel Gasienica <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.