index.js
This file
Path
examples/resource/index.js
93 lines · 2.2 KiB · JavaScript
Last changed by
examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
History of this fileTake it
examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 1–93why, one step back1/**2 * Module dependencies.3 */45var express = require('../../');67var app = module.exports = express();89// Ad-hoc example resource method1011app.resource = function(path, obj) {12 this.get(path, obj.index);13 this.get(path + '/:a..:b.:format?', function(req, res){14 var a = parseInt(req.params.a, 10);15 var b = parseInt(req.params.b, 10);16 var format = req.params.format;17 obj.range(req, res, a, b, format);18 });19 this.get(path + '/:id', obj.show);20 this.delete(path + '/:id', function(req, res){21 var id = parseInt(req.params.id, 10);22 obj.destroy(req, res, id);23 });24};2526// Fake records2728var users = [29 { name: 'tj' }30 , { name: 'ciaran' }31 , { name: 'aaron' }32 , { name: 'guillermo' }33 , { name: 'simon' }34 , { name: 'tobi' }35];3637// Fake controller.3839var User = {40 index: function(req, res){41 res.send(users);42 },43 show: function(req, res){44 res.send(users[req.params.id] || { error: 'Cannot find user' });45 },46 destroy: function(req, res, id){47 var destroyed = id in users;48 delete users[id];49 res.send(destroyed ? 'destroyed' : 'Cannot find user');50 },51 range: function(req, res, a, b, format){52 var range = users.slice(a, b + 1);53 switch (format) {54 case 'json':55 res.send(range);56 break;57 case 'html':58 default:59 var html = '<ul>' + range.map(function(user){60 return '<li>' + user.name + '</li>';61 }).join('\n') + '</ul>';62 res.send(html);63 break;64 }65 }66};6768// curl http://localhost:3000/users -- responds with all users69// curl http://localhost:3000/users/1 -- responds with user 170// curl http://localhost:3000/users/4 -- responds with error71// curl http://localhost:3000/users/1..3 -- responds with several users72// curl -X DELETE http://localhost:3000/users/1 -- deletes the user7374app.resource('/users', User);7576app.get('/', function(req, res){77 res.send([78 '<h1>Examples:</h1> <ul>'79 , '<li>GET /users</li>'80 , '<li>GET /users/1</li>'81 , '<li>GET /users/3</li>'82 , '<li>GET /users/1..3</li>'83 , '<li>GET /users/1..3.json</li>'84 , '<li>DELETE /users/4</li>'85 , '</ul>'86 ].join('\n'));87});8889/* istanbul ignore next */90if (!module.parent) {91 app.listen(3000);92 console.log('Express started on port 3000');93}