app.js
This file
Path
examples/resource/app.js
91 lines · 2.1 KiB · JavaScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than 8ac3e80 point at it.
Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption8ac3e80
lines 1–91why, one step back12/**3 * Module dependencies.4 */56var express = require('../../');78var app = module.exports = express();910// Ad-hoc example resource method1112app.resource = function(path, obj) {13 this.get(path, obj.index);14 this.get(path + '/:a..:b.:format?', function(req, res){15 var a = parseInt(req.params.a, 10)16 , b = parseInt(req.params.b, 10)17 , format = req.params.format;18 obj.range(req, res, a, b, format);19 });20 this.get(path + '/:id', obj.show);21 this.del(path + '/:id', obj.destroy);22};2324// Fake records2526var users = [27 { name: 'tj' }28 , { name: 'ciaran' }29 , { name: 'aaron' }30 , { name: 'guillermo' }31 , { name: 'simon' }32 , { name: 'tobi' }33];3435// Fake controller.3637var User = {38 index: function(req, res){39 res.send(users);40 },41 show: function(req, res){42 res.send(users[req.params.id] || { error: 'Cannot find user' });43 },44 destroy: function(req, res){45 var id = req.params.id;46 var destroyed = id in users;47 delete users[id];48 res.send(destroyed ? 'destroyed' : 'Cannot find user');49 },50 range: function(req, res, a, b, format){51 var range = users.slice(a, b + 1);52 switch (format) {53 case 'json':54 res.send(range);55 break;56 case 'html':57 default:58 var html = '<ul>' + range.map(function(user){59 return '<li>' + user.name + '</li>';60 }).join('\n') + '</ul>';61 res.send(html);62 break;63 }64 }65};6667// curl http://localhost:3000/users -- responds with all users68// curl http://localhost:3000/users/1 -- responds with user 169// curl http://localhost:3000/users/4 -- responds with error70// curl http://localhost:3000/users/1..3 -- responds with several users71// curl -X DELETE http://localhost:3000/users/1 -- deletes the user7273app.resource('/users', User);7475app.get('/', function(req, res){76 res.send([77 '<h1>Examples:</h1> <ul>'78 , '<li>GET /users</li>'79 , '<li>GET /users/1</li>'80 , '<li>GET /users/3</li>'81 , '<li>GET /users/1..3</li>'82 , '<li>GET /users/1..3.json</li>'83 , '<li>DELETE /users/4</li>'84 , '</ul>'85 ].join('\n')); 86});8788if (!module.parent) {89 app.listen(3000);90 console.log('Express started on port 3000');91}