├── .gitignore ├── .gitmodules ├── .npmignore ├── History.md ├── Makefile ├── Readme.md ├── examples ├── content-negotiation.js ├── controllers.js └── controllers │ ├── forum.js │ ├── main.js │ ├── thread.js │ └── user.js ├── index.js ├── package.json └── test ├── fixtures ├── cat.js ├── forum.js ├── pets.format-methods-without-default.js ├── pets.format-methods.js ├── pets.js ├── thread.js └── user.js ├── resource.content-negotiation.test.js ├── resource.test.js └── support └── batch.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visionmedia/express-resource/eed1a1f0acd83053b9fdc309f67829b6f4973333/.gitmodules -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | support 2 | test 3 | -------------------------------------------------------------------------------- /History.md: -------------------------------------------------------------------------------- 1 | 2 | 1.0.0 / 2012-10-06 3 | ================== 4 | 5 | * add 3x support... Closes #55 6 | 7 | 0.2.4 / 2011-12-28 8 | ================== 9 | 10 | * Fixed windows path join. Closes #43 11 | * Fixed _examples/user.js_ 12 | * Fixed resource id when multiple segments are present. Closes #36 13 | 14 | 0.2.3 / 2011-09-23 15 | ================== 16 | 17 | * Fixed logic to allow actions to be defined in any order [Wompt] 18 | 19 | 0.2.2 / 2011-09-08 20 | ================== 21 | 22 | * Added support to allow root resources to have nested resources 23 | * Added auto-load signature support of `(req, id, callback)` 24 | 25 | 0.2.1 / 2011-05-25 26 | ================== 27 | 28 | * Fixed for express 2.3.9. Closes #18 29 | * Added better support for mapping your own actions. Closes #7 30 | 31 | 0.2.0 / 2011-04-09 32 | ================== 33 | 34 | * Added basic content-negotiation support via format extensions 35 | * Added nested resource support 36 | * Added auto-loading support, populating `req.user` etc automatically 37 | * Added another options param to `app.resource()` 38 | * Added `Resource#[http-verb]()` methods to define additional routes 39 | * Added `Resource#map(method, path, fn)` 40 | * Changed; every `Resource` has a `.base` 41 | * Changed; resource id is no longer "id", it's a singular version of the resource name, aka `req.params.user` etc 42 | 43 | 0.1.0 / 2011-03-27 44 | ================== 45 | 46 | * Added support for top-level resources [Daniel Gasienica] 47 | 48 | 0.0.2 / 2011-03-03 49 | ================== 50 | 51 | * Added Express 2.0 support 52 | 53 | 0.0.1 / 2010-09-06 54 | ================== 55 | 56 | * Initial release 57 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | test: 3 | @./node_modules/.bin/mocha \ 4 | --require should \ 5 | --reporter spec 6 | 7 | .PHONY: test -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Express Resource 2 | 3 | express-resource provides resourceful routing to express. For Express 2.x 4 | use a version __below__ 1.0, for Express 3.x use 1.x. 5 | 6 | ## Installation 7 | 8 | npm: 9 | 10 | $ npm install express-resource 11 | 12 | ## Usage 13 | 14 | To get started simply `require('express-resource')`, and this module will monkey-patch Express, enabling resourceful routing by providing the `app.resource()` method. A "resource" is simply an object, which defines one of more of the supported "actions" listed below: 15 | 16 | exports.index = function(req, res){ 17 | res.send('forum index'); 18 | }; 19 | 20 | exports.new = function(req, res){ 21 | res.send('new forum'); 22 | }; 23 | 24 | exports.create = function(req, res){ 25 | res.send('create forum'); 26 | }; 27 | 28 | exports.show = function(req, res){ 29 | res.send('show forum ' + req.params.forum); 30 | }; 31 | 32 | exports.edit = function(req, res){ 33 | res.send('edit forum ' + req.params.forum); 34 | }; 35 | 36 | exports.update = function(req, res){ 37 | res.send('update forum ' + req.params.forum); 38 | }; 39 | 40 | exports.destroy = function(req, res){ 41 | res.send('destroy forum ' + req.params.forum); 42 | }; 43 | 44 | The `app.resource()` method returns a new `Resource` object, which can be used to further map pathnames, nest resources, and more. 45 | 46 | var express = require('express') 47 | , Resource = require('express-resource') 48 | , app = express(); 49 | 50 | app.resource('forums', require('./forum')); 51 | 52 | ## Default Action Mapping 53 | 54 | Actions are then mapped as follows (by default), providing `req.params.forum` which contains the substring where ":forum" is shown below: 55 | 56 | GET /forums -> index 57 | GET /forums/new -> new 58 | POST /forums -> create 59 | GET /forums/:forum -> show 60 | GET /forums/:forum/edit -> edit 61 | PUT /forums/:forum -> update 62 | DELETE /forums/:forum -> destroy 63 | 64 | ## Top-Level Resource 65 | 66 | Specify a top-level resource by omitting the resource name: 67 | 68 | app.resource(require('./forum')); 69 | 70 | Top-level actions are then mapped as follows (by default): 71 | 72 | GET / -> index 73 | GET /new -> new 74 | POST / -> create 75 | GET /:id -> show 76 | GET /:id/edit -> edit 77 | PUT /:id -> update 78 | DELETE /:id -> destroy 79 | 80 | ## Auto-Loading 81 | 82 | 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`: 83 | 84 | 85 | User.load = function(id, fn) { 86 | fn(null, users[id]); 87 | }; 88 | 89 | // or 90 | 91 | User.load = function(req, id, fn) { 92 | fn(null, users[id]); 93 | }; 94 | 95 | app.resource('users', { show: ..., load: User.load }); 96 | 97 | With the auto-loader defined, the `req.user` object will 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: 98 | 99 | app.resource('users', require('./user'), { load: User.load }); 100 | 101 | Finally we can utilize the `Resource#load(fn)` method, which again is functionally equivalent: 102 | 103 | var user = app.resource('users', require('./user')); 104 | user.load(User.load); 105 | 106 | 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: 107 | 108 | var forums = app.resource('forums', require('resources/forums'), { load: Forum.get }); 109 | var threads = app.resource('threads', require('resources/threads'), { load: Thread.get }); 110 | 111 | forums.add(threads); 112 | 113 | 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. 114 | 115 | ## Content-Negotiation 116 | 117 | 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`. 118 | 119 | var pets = ['tobi', 'jane', 'loki']; 120 | 121 | exports.index = function(req, res){ 122 | switch (req.format) { 123 | case 'json': 124 | res.send(pets); 125 | break; 126 | case 'xml': 127 | res.send('' + pets.map(function(pet){ 128 | return '' + pet + ''; 129 | }).join('') + ''); 130 | break; 131 | default: 132 | res.send(406); 133 | } 134 | }; 135 | 136 | The following is equivalent, however we separate the logic into several callbacks, each representing a format. 137 | 138 | exports.index = { 139 | json: function(req, res){ 140 | res.send(pets); 141 | }, 142 | 143 | xml: function(req, res){ 144 | res.send('' + pets.map(function(pet){ 145 | return '' + pet + ''; 146 | }).join('') + ''); 147 | } 148 | }; 149 | 150 | We may also provide a `default` format, invoked when either no extension is given, or one that does not match another method is given: 151 | 152 | 153 | exports.default = function(req, res){ 154 | res.send('Unsupported format "' + req.format + '"', 406); 155 | }; 156 | 157 | 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'`. 158 | 159 | app.resource('users', actions, { format: 'json' }); 160 | 161 | ## Running Tests 162 | 163 | First make sure you have the submodules: 164 | 165 | $ git submodule update --init 166 | 167 | Then run the tests: 168 | 169 | $ make test 170 | 171 | ## License 172 | 173 | The MIT License 174 | 175 | Copyright (c) 2010-2012 TJ Holowaychuk 176 | Copyright (c) 2011 Daniel Gasienica 177 | 178 | Permission is hereby granted, free of charge, to any person obtaining 179 | a copy of this software and associated documentation files (the 180 | 'Software'), to deal in the Software without restriction, including 181 | without limitation the rights to use, copy, modify, merge, publish, 182 | distribute, sublicense, and/or sell copies of the Software, and to 183 | permit persons to whom the Software is furnished to do so, subject to 184 | the following conditions: 185 | 186 | The above copyright notice and this permission notice shall be 187 | included in all copies or substantial portions of the Software. 188 | 189 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, 190 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 191 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 192 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 193 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 194 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 195 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 196 | -------------------------------------------------------------------------------- /examples/content-negotiation.js: -------------------------------------------------------------------------------- 1 | 2 | var express = require('express') 3 | , resource = require('..') 4 | , app = express(); 5 | 6 | var users = app.resource('users', require('./controllers/user')); 7 | 8 | app.get('/', function(req, res){ 9 | res.send('View users'); 10 | }); 11 | 12 | app.listen(3000); 13 | console.log('Listening on :3000'); -------------------------------------------------------------------------------- /examples/controllers.js: -------------------------------------------------------------------------------- 1 | 2 | var express = require('express') 3 | , resource = require('..') 4 | , app = express(); 5 | 6 | var main = app.resource(require('./controllers/main')); 7 | var forums = app.resource('forums', require('./controllers/forum')); 8 | var threads = app.resource('threads', require('./controllers/thread')); 9 | forums.add(threads); 10 | 11 | app.listen(3000); 12 | console.log('Listening on :3000'); -------------------------------------------------------------------------------- /examples/controllers/forum.js: -------------------------------------------------------------------------------- 1 | 2 | exports.index = function(req, res){ 3 | res.send('forum index'); 4 | }; 5 | 6 | exports.new = function(req, res){ 7 | res.send('new forum'); 8 | }; 9 | 10 | exports.create = function(req, res){ 11 | res.send('create forum'); 12 | }; 13 | 14 | exports.show = function(req, res){ 15 | res.send('show forum ' + req.forum.title); 16 | }; 17 | 18 | exports.edit = function(req, res){ 19 | res.send('edit forum ' + req.forum.title); 20 | }; 21 | 22 | exports.update = function(req, res){ 23 | res.send('update forum ' + req.forum.title); 24 | }; 25 | 26 | exports.destroy = function(req, res){ 27 | res.send('destroy forum ' + req.forum.title); 28 | }; 29 | 30 | exports.load = function(id, fn){ 31 | process.nextTick(function(){ 32 | fn(null, { title: 'Ferrets' }); 33 | }); 34 | }; 35 | -------------------------------------------------------------------------------- /examples/controllers/main.js: -------------------------------------------------------------------------------- 1 | 2 | exports.index = function(req, res){ 3 | res.send('main index'); 4 | } -------------------------------------------------------------------------------- /examples/controllers/thread.js: -------------------------------------------------------------------------------- 1 | 2 | exports.index = function(req, res){ 3 | res.send('forum ' + req.forum.title + ' threads'); 4 | }; 5 | 6 | exports.new = function(req, res){ 7 | res.send('new forum ' + req.forum.title + ' thread'); 8 | }; 9 | 10 | exports.create = function(req, res){ 11 | res.send('forum ' + req.forum.title + ' thread created'); 12 | }; 13 | 14 | exports.show = function(req, res){ 15 | res.send('forum ' + req.forum.title + ' thread ' + req.thread.title); 16 | }; 17 | 18 | exports.edit = function(req, res){ 19 | res.send('editing forum ' + req.forum.title + ' thread ' + req.thread.title); 20 | }; 21 | 22 | exports.load = function(id, fn){ 23 | process.nextTick(function(){ 24 | fn(null, { title: 'How do you take care of ferrets?' }); 25 | }); 26 | }; 27 | -------------------------------------------------------------------------------- /examples/controllers/user.js: -------------------------------------------------------------------------------- 1 | 2 | var users = []; 3 | 4 | users.push({ name: 'tobi' }); 5 | users.push({ name: 'loki' }); 6 | users.push({ name: 'jane' }); 7 | 8 | /** 9 | * GET index. 10 | */ 11 | 12 | exports.index = { 13 | html: function(req, res){ 14 | res.send('

Users

' 15 | + users.map(function(user, id){ 16 | return '' + user.name + ''; 17 | }).join('\n')); 18 | }, 19 | 20 | json: function(req, res){ 21 | res.send(users); 22 | }, 23 | 24 | xml: function(req, res){ 25 | res.send(users.map(function(user){ 26 | return '' + user.name + '' 27 | }).join('')); 28 | } 29 | }; 30 | 31 | /** 32 | * POST create. 33 | */ 34 | 35 | exports.create = function(req, res){ 36 | res.send('created'); 37 | }; 38 | 39 | /** 40 | * GET show. 41 | */ 42 | 43 | exports.show = { 44 | html: function(req, res){ 45 | res.send('

' + req.user.name + '

'); 46 | }, 47 | 48 | json: function(req, res){ 49 | res.send(req.user); 50 | }, 51 | 52 | xml: function(req, res){ 53 | res.send('' + req.user.name + ''); 54 | } 55 | }; 56 | 57 | /** 58 | * Auto-load user re-source for actions. 59 | */ 60 | 61 | exports.load = function(id, fn){ 62 | var user = users[id]; 63 | if (!user) return fn(new Error('not found')); 64 | process.nextTick(function(){ 65 | fn(null, user); 66 | }); 67 | } -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 2 | /*! 3 | * Express - Resource 4 | * Copyright(c) 2010-2012 TJ Holowaychuk 5 | * Copyright(c) 2011 Daniel Gasienica 6 | * MIT Licensed 7 | */ 8 | 9 | /** 10 | * Module dependencies. 11 | */ 12 | 13 | var express = require('express') 14 | , methods = require('methods') 15 | , debug = require('debug')('express-resource') 16 | , lingo = require('lingo') 17 | , app = express.application 18 | , en = lingo.en; 19 | 20 | /** 21 | * Pre-defined action ordering. 22 | */ 23 | 24 | var orderedActions = [ 25 | 'index' // GET / 26 | , 'new' // GET /new 27 | , 'create' // POST / 28 | , 'show' // GET /:id 29 | , 'edit' // GET /edit/:id 30 | , 'update' // PUT /:id 31 | , 'patch' // PATCH /:id 32 | , 'destroy' // DEL /:id 33 | ]; 34 | 35 | /** 36 | * Expose `Resource`. 37 | */ 38 | 39 | module.exports = Resource; 40 | 41 | /** 42 | * Initialize a new `Resource` with the given `name` and `actions`. 43 | * 44 | * @param {String} name 45 | * @param {Object} actions 46 | * @param {Server} app 47 | * @api private 48 | */ 49 | 50 | function Resource(name, actions, app) { 51 | this.name = name; 52 | this.app = app; 53 | this.routes = {}; 54 | actions = actions || {}; 55 | this.base = actions.base || '/'; 56 | if ('/' != this.base[this.base.length - 1]) this.base += '/'; 57 | this.format = actions.format; 58 | this.id = actions.id || this.defaultId; 59 | this.param = ':' + this.id; 60 | 61 | // default actions 62 | for (var i = 0, key; i < orderedActions.length; ++i) { 63 | key = orderedActions[i]; 64 | if (actions[key]) this.mapDefaultAction(key, actions[key]); 65 | } 66 | 67 | // auto-loader 68 | if (actions.load) this.load(actions.load); 69 | }; 70 | 71 | /** 72 | * Set the auto-load `fn`. 73 | * 74 | * @param {Function} fn 75 | * @return {Resource} for chaining 76 | * @api public 77 | */ 78 | 79 | Resource.prototype.load = function(fn){ 80 | var self = this 81 | , id = this.id; 82 | 83 | this.loadFunction = fn; 84 | this.app.param(this.id, function(req, res, next){ 85 | function callback(err, obj){ 86 | if (err) return next(err); 87 | // TODO: ideally we should next() passed the 88 | // route handler 89 | if (null == obj) return res.send(404); 90 | req[id] = obj; 91 | next(); 92 | }; 93 | 94 | // Maintain backward compatibility 95 | if (2 == fn.length) { 96 | fn(req.params[id], callback); 97 | } else { 98 | fn(req, req.params[id], callback); 99 | } 100 | }); 101 | 102 | return this; 103 | }; 104 | 105 | /** 106 | * Retun this resource's default id string. 107 | * 108 | * @return {String} 109 | * @api private 110 | */ 111 | 112 | Resource.prototype.__defineGetter__('defaultId', function(){ 113 | return this.name 114 | ? en.singularize(this.name.split('/').pop()) 115 | : 'id'; 116 | }); 117 | 118 | /** 119 | * Map http `method` and optional `path` to `fn`. 120 | * 121 | * @param {String} method 122 | * @param {String|Function|Object} path 123 | * @param {Function} fn 124 | * @return {Resource} for chaining 125 | * @api public 126 | */ 127 | 128 | Resource.prototype.map = function(method, path, fn){ 129 | var self = this 130 | , orig = path; 131 | 132 | if (method instanceof Resource) return this.add(method); 133 | if ('function' == typeof path) fn = path, path = ''; 134 | if ('object' == typeof path) fn = path, path = ''; 135 | if ('/' == path[0]) path = path.substr(1); 136 | else path = path ? this.param + '/' + path : this.param; 137 | method = method.toLowerCase(); 138 | 139 | // setup route pathname 140 | var route = this.base + (this.name || ''); 141 | if (this.name && path) route += '/'; 142 | route += path; 143 | route += '.:format?'; 144 | 145 | // register the route so we may later remove it 146 | (this.routes[method] = this.routes[method] || {})[route] = { 147 | method: method 148 | , path: route 149 | , orig: orig 150 | , fn: fn 151 | }; 152 | 153 | // apply the route 154 | this.app[method](route, function(req, res, next){ 155 | req.format = req.params.format || req.format || self.format; 156 | if (req.format) res.type(req.format); 157 | if ('object' == typeof fn) { 158 | if (fn[req.format]) { 159 | fn[req.format](req, res, next); 160 | } else { 161 | res.format(fn); 162 | } 163 | } else { 164 | fn(req, res, next); 165 | } 166 | }); 167 | 168 | return this; 169 | }; 170 | 171 | /** 172 | * Nest the given `resource`. 173 | * 174 | * @param {Resource} resource 175 | * @return {Resource} for chaining 176 | * @see Resource#map() 177 | * @api public 178 | */ 179 | 180 | Resource.prototype.add = function(resource){ 181 | var app = this.app 182 | , routes 183 | , route; 184 | 185 | // relative base 186 | resource.base = this.base 187 | + (this.name ? this.name + '/': '') 188 | + this.param + '/'; 189 | 190 | // re-define previous actions 191 | for (var method in resource.routes) { 192 | routes = resource.routes[method]; 193 | for (var key in routes) { 194 | route = routes[key]; 195 | delete routes[key]; 196 | if (method == 'del') method = 'delete'; 197 | app.routes[method].forEach(function(route, i){ 198 | if (route.path == key) { 199 | app.routes[method].splice(i, 1); 200 | } 201 | }) 202 | resource.map(route.method, route.orig, route.fn); 203 | } 204 | } 205 | 206 | return this; 207 | }; 208 | 209 | /** 210 | * Map the given action `name` with a callback `fn()`. 211 | * 212 | * @param {String} key 213 | * @param {Function} fn 214 | * @api private 215 | */ 216 | 217 | Resource.prototype.mapDefaultAction = function(key, fn){ 218 | switch (key) { 219 | case 'index': 220 | this.get('/', fn); 221 | break; 222 | case 'new': 223 | this.get('/new', fn); 224 | break; 225 | case 'create': 226 | this.post('/', fn); 227 | break; 228 | case 'show': 229 | this.get(fn); 230 | break; 231 | case 'edit': 232 | this.get('edit', fn); 233 | break; 234 | case 'update': 235 | this.put(fn); 236 | break; 237 | case 'patch': 238 | this.patch(fn); 239 | break; 240 | case 'destroy': 241 | this.del(fn); 242 | break; 243 | } 244 | }; 245 | 246 | /** 247 | * Setup http verb methods. 248 | */ 249 | 250 | methods.concat(['del', 'all']).forEach(function(method){ 251 | Resource.prototype[method] = function(path, fn){ 252 | if ('function' == typeof path 253 | || 'object' == typeof path) fn = path, path = ''; 254 | this.map(method, path, fn); 255 | return this; 256 | } 257 | }); 258 | 259 | /** 260 | * Define a resource with the given `name` and `actions`. 261 | * 262 | * @param {String|Object} name or actions 263 | * @param {Object} actions 264 | * @return {Resource} 265 | * @api public 266 | */ 267 | 268 | app.resource = function(name, actions, opts){ 269 | var options = actions || {}; 270 | if ('object' == typeof name) actions = name, name = null; 271 | if (options.id) actions.id = options.id; 272 | this.resources = this.resources || {}; 273 | if (!actions) return this.resources[name] || new Resource(name, null, this); 274 | for (var key in opts) options[key] = opts[key]; 275 | var res = this.resources[name] = new Resource(name, actions, this); 276 | return res; 277 | }; 278 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express-resource", 3 | "description": "Resourceful routing for express", 4 | "version": "1.0.0", 5 | "homepage": "https://github.com/visionmedia/express-resource", 6 | "author": "TJ Holowaychuk ", 7 | "contributors": [ 8 | { 9 | "name": "Daniel Gasienica", 10 | "email": "daniel@gasienica.ch" 11 | } 12 | ], 13 | "dependencies": { 14 | "lingo": ">= 0.0.4", 15 | "methods": "0.0.1", 16 | "debug": "*" 17 | }, 18 | "devDependencies": { 19 | "connect": "2.x", 20 | "express": "3.x", 21 | "ejs": "0.4.x", 22 | "qs": "0.1.x", 23 | "mocha": "*", 24 | "should": "*", 25 | "supertest": "0.1.2" 26 | }, 27 | "keywords": [ 28 | "express", 29 | "rest", 30 | "resource" 31 | ], 32 | "main": "index", 33 | "engines": { 34 | "node": "*" 35 | }, 36 | "repository": { 37 | "type": "git", 38 | "url": "https://github.com/visionmedia/express-resource.git" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /test/fixtures/cat.js: -------------------------------------------------------------------------------- 1 | 2 | exports.index = function(req, res){ 3 | res.send('list of cats'); 4 | }; 5 | 6 | exports.new = function(req, res){ 7 | res.send('new cat'); 8 | }; -------------------------------------------------------------------------------- /test/fixtures/forum.js: -------------------------------------------------------------------------------- 1 | 2 | exports.index = function(req, res){ 3 | res.send('forum index'); 4 | }; 5 | 6 | exports.new = function(req, res){ 7 | res.send('new forum'); 8 | }; 9 | 10 | exports.create = function(req, res){ 11 | res.send('create forum'); 12 | }; 13 | 14 | exports.show = function(req, res){ 15 | res.send('show forum ' + req.params.forum); 16 | }; 17 | 18 | exports.edit = function(req, res){ 19 | res.send('edit forum ' + req.params.forum); 20 | }; 21 | 22 | exports.update = function(req, res){ 23 | res.send('update forum ' + req.params.forum); 24 | }; 25 | 26 | exports.patch = function(req, res){ 27 | res.send('patch forum ' + req.params.forum); 28 | }; 29 | 30 | exports.destroy = function(req, res){ 31 | res.send('destroy forum ' + req.params.forum); 32 | }; 33 | 34 | exports.Forum = { get: function(id, fn){ 35 | process.nextTick(function(){ 36 | fn(null, { title: 'Ferrets' }); 37 | }); 38 | }}; 39 | -------------------------------------------------------------------------------- /test/fixtures/pets.format-methods-without-default.js: -------------------------------------------------------------------------------- 1 | 2 | var pets = ['tobi', 'jane', 'loki']; 3 | 4 | exports.index = { 5 | json: function(req, res){ 6 | res.send(pets); 7 | }, 8 | 9 | xml: function(req, res){ 10 | res.send('' + pets.map(function(pet){ 11 | return '' + pet + ''; 12 | }).join('') + ''); 13 | } 14 | }; 15 | 16 | exports.load = function(id, fn){ 17 | fn(null, pets[id]); 18 | }; -------------------------------------------------------------------------------- /test/fixtures/pets.format-methods.js: -------------------------------------------------------------------------------- 1 | 2 | var pets = ['tobi', 'jane', 'loki']; 3 | 4 | exports.index = { 5 | json: function(req, res){ 6 | res.send(pets); 7 | }, 8 | 9 | xml: function(req, res){ 10 | res.send('' + pets.map(function(pet){ 11 | return '' + pet + ''; 12 | }).join('') + ''); 13 | }, 14 | 15 | default: function(req, res){ 16 | res.send('Unsupported format', 406); 17 | } 18 | }; 19 | 20 | exports.load = function(id, fn){ 21 | fn(null, pets[id]); 22 | }; -------------------------------------------------------------------------------- /test/fixtures/pets.js: -------------------------------------------------------------------------------- 1 | 2 | var pets = ['tobi', 'jane', 'loki']; 3 | 4 | exports.index = function(req, res){ 5 | switch (req.format) { 6 | case 'json': 7 | res.send(pets); 8 | break; 9 | case 'xml': 10 | res.send('' + pets.map(function(pet){ 11 | return '' + pet + ''; 12 | }).join('') + ''); 13 | break; 14 | default: 15 | res.send(406); 16 | } 17 | }; 18 | 19 | exports.show = function(req, res){ 20 | switch (req.format) { 21 | case 'json': 22 | res.end(JSON.stringify(req.pet)); 23 | break; 24 | case 'xml': 25 | res.end('' + req.pet + ''); 26 | break; 27 | default: 28 | res.send(406); 29 | } 30 | }; 31 | 32 | exports.destroy = function(req, res){ 33 | switch (req.format) { 34 | case 'json': 35 | res.send({ message: 'pet removed' }); 36 | break; 37 | case 'xml': 38 | res.send('pet removed'); 39 | break; 40 | default: 41 | res.send(406); 42 | } 43 | }; 44 | 45 | exports.load = function(id, fn){ 46 | fn(null, pets[id]); 47 | }; -------------------------------------------------------------------------------- /test/fixtures/thread.js: -------------------------------------------------------------------------------- 1 | 2 | exports.index = function(req, res){ 3 | res.send('thread index of forum ' + req.params.forum); 4 | }; 5 | 6 | exports.new = function(req, res){ 7 | res.send('new thread'); 8 | }; 9 | 10 | exports.create = function(req, res){ 11 | res.send('create thread'); 12 | }; 13 | 14 | exports.show = function(req, res){ 15 | res.send('show thread ' + req.params.thread + ' of forum ' + req.params.forum); 16 | }; 17 | 18 | exports.edit = function(req, res){ 19 | res.send('edit thread ' + req.params.thread + ' of forum ' + req.params.forum); 20 | }; 21 | 22 | exports.update = function(req, res){ 23 | res.send('update thread ' + req.params.thread + ' of forum ' + req.params.forum); 24 | }; 25 | 26 | exports.patch = function(req, res){ 27 | res.send('patch thread ' + req.params.thread + ' of forum ' + req.params.forum); 28 | }; 29 | 30 | exports.destroy = function(req, res){ 31 | res.send('destroy thread ' + req.params.thread + ' of forum ' + req.params.forum); 32 | }; 33 | 34 | exports.Thread = { get: function(id, fn){ 35 | process.nextTick(function(){ 36 | fn(null, { title: 'Tobi rules' }); 37 | }); 38 | }}; 39 | -------------------------------------------------------------------------------- /test/fixtures/user.js: -------------------------------------------------------------------------------- 1 | 2 | exports.User = { get: function(id, fn){ 3 | process.nextTick(function(){ 4 | fn(null, { name: 'tj' }); 5 | }); 6 | }}; 7 | -------------------------------------------------------------------------------- /test/resource.content-negotiation.test.js: -------------------------------------------------------------------------------- 1 | 2 | var assert = require('assert') 3 | , express = require('express') 4 | , request = require('supertest') 5 | , batch = require('./support/batch') 6 | , Resource = require('..'); 7 | 8 | describe('app.resource()', function(){ 9 | it('should support content-negotiation via extension', function(done){ 10 | var app = express(); 11 | var next = batch(done); 12 | 13 | app.set('json spaces', 0); 14 | app.resource('pets', require('./fixtures/pets')); 15 | 16 | request(app) 17 | .get('/pets.html') 18 | .expect(406, next()); 19 | 20 | request(app) 21 | .get('/pets.json') 22 | .expect('["tobi","jane","loki"]', next()); 23 | 24 | request(app) 25 | .get('/pets.xml') 26 | .expect('tobijaneloki', next()); 27 | 28 | request(app) 29 | .get('/pets/1.json') 30 | .expect('"jane"', next()); 31 | 32 | request(app) 33 | .get('/pets/0.xml') 34 | .expect('tobi', next()); 35 | 36 | request(app) 37 | .del('/pets/0.xml') 38 | .expect('pet removed', next()); 39 | 40 | request(app) 41 | .del('/pets/0.json') 42 | .expect('{"message":"pet removed"}', next()); 43 | }) 44 | 45 | it('should support format methods', function(done){ 46 | var app = express(); 47 | var next = batch(done); 48 | app.set('json spaces', 0); 49 | app.resource('pets', require('./fixtures/pets.format-methods')); 50 | 51 | request(app) 52 | .get('/pets.xml') 53 | .expect('tobijaneloki', next()); 54 | 55 | request(app) 56 | .get('/pets.json') 57 | .expect('["tobi","jane","loki"]', next()); 58 | 59 | request(app) 60 | .get('/pets') 61 | .expect('["tobi","jane","loki"]', next()); 62 | }) 63 | }) 64 | 65 | describe('app.VERB()', function(){ 66 | it('should map additional routes', function(done){ 67 | var app = express(); 68 | 69 | app.set('json spaces', 0); 70 | app.use(express.bodyParser()); 71 | 72 | var pets = app.resource('pets'); 73 | var toys = app.resource('toys'); 74 | var values = ['balls', 'platforms', 'tunnels']; 75 | 76 | toys.get('/types', function(req, res){ 77 | res.send(values); 78 | }); 79 | 80 | request(app) 81 | .get('/toys/types') 82 | .expect('["balls","platforms","tunnels"]', done); 83 | }) 84 | 85 | it('should map format objects', function(done){ 86 | var app = express(); 87 | var next = batch(done); 88 | 89 | app.set('json spaces', 0); 90 | app.use(express.bodyParser()); 91 | 92 | var toys = app.resource('toys'); 93 | var values = ['balls', 'platforms', 'tunnels']; 94 | 95 | toys.get('/types', { 96 | json: function(req, res){ 97 | res.send(values); 98 | }, 99 | 100 | 'text/plain': function(req, res){ 101 | res.send(values.join('\n')); 102 | }, 103 | 104 | xml: function(req, res){ 105 | res.send(''); 106 | } 107 | }); 108 | 109 | request(app) 110 | .get('/toys/types') 111 | .expect('["balls","platforms","tunnels"]', next()); 112 | 113 | request(app) 114 | .get('/toys/types') 115 | .set('Accept', 'text/*') 116 | .expect('balls\nplatforms\ntunnels', next()); 117 | 118 | request(app) 119 | .get('/toys/types.xml') 120 | .expect('', next()); 121 | }) 122 | }) 123 | 124 | describe('Resource#add(resource)', function(){ 125 | it('should support nested resources', function(done){ 126 | var app = express(); 127 | app.set('json spaces', 0); 128 | 129 | var users = app.resource('users'); 130 | var pets = app.resource('pets', require('./fixtures/pets')); 131 | users.add(pets); 132 | 133 | request(app) 134 | .get('/users/1/pets.json') 135 | .expect('["tobi","jane","loki"]', done); 136 | }) 137 | }) -------------------------------------------------------------------------------- /test/resource.test.js: -------------------------------------------------------------------------------- 1 | 2 | var assert = require('assert') 3 | , express = require('express') 4 | , Resource = require('..') 5 | , request = require('supertest') 6 | , batch = require('./support/batch'); 7 | 8 | describe('app.resource(name)', function(){ 9 | it('should return a pre-defined resource', function(){ 10 | var app = express(); 11 | app.resource('users', { index: function(){} }); 12 | app.resource('users').should.be.an.instanceof(Resource); 13 | app.resource('foo').should.be.an.instanceof(Resource); 14 | }) 15 | }) 16 | 17 | describe('app.resource()', function(){ 18 | it('should map CRUD actions', function(done){ 19 | var app = express(); 20 | var next = batch(done); 21 | 22 | var ret = app.resource('forums', require('./fixtures/forum')); 23 | ret.should.be.an.instanceof(Resource); 24 | 25 | request(app) 26 | .get('/forums') 27 | .expect('forum index', next()); 28 | 29 | request(app) 30 | .get('/forums/new') 31 | .expect('new forum', next()); 32 | 33 | request(app) 34 | .post('/forums') 35 | .expect('create forum', next()); 36 | 37 | request(app) 38 | .get('/forums/5') 39 | .expect('show forum 5', next()); 40 | 41 | request(app) 42 | .get('/forums/5/edit') 43 | .expect('edit forum 5', next()); 44 | 45 | request(app) 46 | .put('/forums/5') 47 | .expect('update forum 5', next()); 48 | 49 | request(app) 50 | .patch('/forums/5') 51 | .expect('patch forum 5', next()); 52 | 53 | request(app) 54 | .del('/forums/5') 55 | .expect('destroy forum 5', next()); 56 | }) 57 | 58 | it('should support root resources', function(done){ 59 | var app = express(); 60 | var next = batch(done); 61 | var forum = app.resource('forums', require('./fixtures/forum')); 62 | var thread = app.resource('threads', require('./fixtures/thread')); 63 | forum.map(thread); 64 | 65 | request(app) 66 | .get('/forums') 67 | .expect('forum index', next()); 68 | 69 | request(app) 70 | .get('/forums/new') 71 | .expect('new forum', next()); 72 | 73 | request(app) 74 | .post('/forums') 75 | .expect('create forum', next()); 76 | 77 | request(app) 78 | .get('/forums/12') 79 | .expect('show forum 12', next()); 80 | 81 | request(app) 82 | .get('/forums/12/edit') 83 | .expect('edit forum 12', next()); 84 | 85 | request(app) 86 | .put('/forums/12') 87 | .expect('update forum 12', next()); 88 | 89 | request(app) 90 | .patch('/forums/12') 91 | .expect('patch forum 12', next()); 92 | 93 | request(app) 94 | .del('/forums/12') 95 | .expect('destroy forum 12', next()); 96 | 97 | request(app) 98 | .get('/forums/12/threads') 99 | .expect('thread index of forum 12', next()); 100 | 101 | request(app) 102 | .get('/forums/12/threads/new') 103 | .expect('new thread', next()); 104 | 105 | request(app) 106 | .post('/forums/12/threads') 107 | .expect('create thread', next()); 108 | 109 | request(app) 110 | .get('/forums/12/threads/50') 111 | .expect('show thread 50 of forum 12', next()); 112 | 113 | request(app) 114 | .get('/forums/12/threads/50/edit') 115 | .expect('edit thread 50 of forum 12', next()); 116 | 117 | request(app) 118 | .put('/forums/12/threads/50') 119 | .expect('update thread 50 of forum 12', next()); 120 | 121 | request(app) 122 | .patch('/forums/12/threads/50') 123 | .expect('patch thread 50 of forum 12', next()); 124 | 125 | request(app) 126 | .del('/forums/12/threads/50') 127 | .expect('destroy thread 50 of forum 12', next()) 128 | }) 129 | 130 | describe('"id" option', function(){ 131 | it('should allow overriding the default', function(done){ 132 | var app = express(); 133 | var next = batch(done); 134 | 135 | app.resource('users', { 136 | id: 'uid', 137 | show: function(req, res){ 138 | res.send(req.params.uid); 139 | } 140 | }); 141 | 142 | request(app) 143 | .get('/users') 144 | .expect(404, next()); 145 | 146 | request(app) 147 | .get('/users/10') 148 | .expect('10', next()); 149 | }) 150 | }) 151 | 152 | describe('with several segments', function(){ 153 | it('should work', function(done){ 154 | var app = express(); 155 | var next = batch(done); 156 | var cat = app.resource('api/cat', require('./fixtures/cat')); 157 | 158 | request(app) 159 | .get('/api/cat') 160 | .expect('list of cats', next()); 161 | 162 | request(app) 163 | .get('/api/cat/new') 164 | .expect('new cat', next()); 165 | }) 166 | }) 167 | 168 | it('should allow configuring routes', function(done){ 169 | var app = express(); 170 | var next = batch(done); 171 | var Forum = require('./fixtures/forum').Forum; 172 | 173 | function load(id, fn) { fn(null, "User"); } 174 | 175 | var actions = { 176 | login: function(req, res){ 177 | res.end('login'); 178 | }, 179 | logout: function(req, res){ 180 | res.end('logout'); 181 | } 182 | }; 183 | 184 | var users = app.resource('users', actions, { load: load }); 185 | users.map('get', 'login', actions.login); 186 | users.map('get', '/logout', actions.logout); 187 | 188 | request(app) 189 | .get('/users/1/login') 190 | .expect('login', next()); 191 | 192 | request(app) 193 | .get('/users/logout') 194 | .expect('logout', next()); 195 | }) 196 | 197 | describe('autoloading', function(){ 198 | describe('when no resource is found', function(){ 199 | it('should not invoke the callback', function(done){ 200 | var app = express(); 201 | 202 | function load(id, fn) { fn(); } 203 | var actions = { show: function(){ 204 | assert.fail('called show when loader failed'); 205 | }}; 206 | 207 | app.resource('pets', actions, { load: load }); 208 | 209 | request(app) 210 | .get('/pets/0') 211 | .expect(404, done); 212 | }) 213 | }) 214 | 215 | describe('when a resource is found', function(){ 216 | it('should invoke the callback', function(done){ 217 | var app = express(); 218 | var Forum = require('./fixtures/forum').Forum; 219 | 220 | var actions = { show: function(req, res){ 221 | res.end(req.forum.title); 222 | }}; 223 | 224 | var forum = app.resource('forum', actions); 225 | forum.load(Forum.get); 226 | 227 | request(app) 228 | .get('/forum/12') 229 | .expect('Ferrets', done); 230 | }) 231 | 232 | it('should work recursively', function(done){ 233 | var app = express(); 234 | var Forum = require('./fixtures/forum').Forum; 235 | var Thread = require('./fixtures/thread').Thread; 236 | 237 | var actions = { show: function(req, res){ 238 | res.end(req.forum.title + ': ' + req.thread.title); 239 | }}; 240 | 241 | var forum = app.resource('forum', { load: Forum.get }); 242 | var threads = app.resource('thread', actions, { load: Thread.get }); 243 | 244 | forum.add(threads); 245 | 246 | request(app) 247 | .get('/forum/12/thread/1') 248 | .expect('Ferrets: Tobi rules', done); 249 | }) 250 | }) 251 | }) 252 | }) 253 | -------------------------------------------------------------------------------- /test/support/batch.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = function(done) { 3 | var pending = 0; 4 | var finished = false; 5 | return function(){ 6 | ++pending; 7 | return function(err){ 8 | if (finished) return; 9 | if (err) return finished = true, done(err); 10 | --pending || done(); 11 | } 12 | } 13 | }; --------------------------------------------------------------------------------