app.js
This file
Path
examples/resource/app.js
92 lines · 2.2 KiB · JavaScript
Last changed by
renamed example to paramsTj Holowaychukbefore adoption635fac7
History of this fileTake it
The walk stopped after 200 commits: lines older than 2bfdfe3 point at it.
Fixed for middleware stacked via createServer()Tj Holowaychukbefore adoption2bfdfe3
line 1why, one step back1renamed example to paramsTj Holowaychukbefore adoption635fac7
lines 2–4why, one step back2// Expose modules in ./support for demo purposes3require.paths.unshift(__dirname + '/../../support');4Fixed for middleware stacked via createServer()Tj Holowaychukbefore adoption2bfdfe3
lines 5–92why, one step back5/**6 * Module dependencies.7 */89var express = require('../../lib/express');1011var app = express.createServer();1213// Ad-hoc example resource method1415app.resource = function(path, obj) {16 this.get(path, obj.index);17 this.get(path + '/:a..:b.:format?', function(req, res){18 var a = parseInt(req.params.a, 10)19 , b = parseInt(req.params.b, 10)20 , format = req.params.format;21 obj.range(req, res, a, b, format);22 });23 this.get(path + '/:id', obj.show);24 this.del(path + '/:id', obj.destroy);25};2627// Fake records2829var users = [30 { name: 'tj' }31 , { name: 'ciaran' }32 , { name: 'aaron' }33 , { name: 'guillermo' }34 , { name: 'simon' }35 , { name: 'tobi' }36];3738// Fake controller.3940var User = {41 index: function(req, res){42 res.send(users);43 },44 show: function(req, res){45 res.send(users[req.params.id] || { error: 'Cannot find user' });46 },47 destroy: function(req, res){48 var id = req.params.id;49 var destroyed = id in users;50 delete users[id];51 res.send(destroyed ? 'destroyed' : 'Cannot find user');52 },53 range: function(req, res, a, b, format){54 var range = users.slice(a, b + 1);55 switch (format) {56 case 'json':57 res.send(range);58 break;59 case 'html':60 default:61 var html = '<ul>' + range.map(function(user){62 return '<li>' + user.name + '</li>';63 }).join('\n') + '</ul>';64 res.send(html);65 break;66 }67 }68};6970// curl http://localhost:3000/users -- responds with all users71// curl http://localhost:3000/users/1 -- responds with user 172// curl http://localhost:3000/users/4 -- responds with error73// curl http://localhost:3000/users/1..3 -- responds with several users74// curl -X DELETE http://localhost:3000/users/1 -- deletes the user7576app.resource('/users', User);7778app.get('/', function(req, res){79 res.send([80 '<h1>Examples:</h1> <ul>'81 , '<li>GET /users</li>'82 , '<li>GET /users/1</li>'83 , '<li>GET /users/3</li>'84 , '<li>GET /users/1..3</li>'85 , '<li>GET /users/1..3.json</li>'86 , '<li>DELETE /users/4</li>'87 , '</ul>'88 ].join('\n')); 89});9091app.listen(3000);92console.log('Express app started on port 3000');