Skip to content
Myr

app.js

This file

Path

examples/resource/app.js

94 lines · 2.2 KiB · JavaScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than 9f4968a point at it.

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 1–94why, one step back
1
2/**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.delete(path + '/:id', function(req, res){22 var id = parseInt(req.params.id, 10);23 obj.destroy(req, res, id);24 });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, id){48 var destroyed = id in users;49 delete users[id];50 res.send(destroyed ? 'destroyed' : 'Cannot find user');51 },52 range: function(req, res, a, b, format){53 var range = users.slice(a, b + 1);54 switch (format) {55 case 'json':56 res.send(range);57 break;58 case 'html':59 default:60 var html = '<ul>' + range.map(function(user){61 return '<li>' + user.name + '</li>';62 }).join('\n') + '</ul>';63 res.send(html);64 break;65 }66 }67};6869// curl http://localhost:3000/users -- responds with all users70// curl http://localhost:3000/users/1 -- responds with user 171// curl http://localhost:3000/users/4 -- responds with error72// curl http://localhost:3000/users/1..3 -- responds with several users73// curl -X DELETE http://localhost:3000/users/1 -- deletes the user7475app.resource('/users', User);7677app.get('/', function(req, res){78 res.send([79 '<h1>Examples:</h1> <ul>'80 , '<li>GET /users</li>'81 , '<li>GET /users/1</li>'82 , '<li>GET /users/3</li>'83 , '<li>GET /users/1..3</li>'84 , '<li>GET /users/1..3.json</li>'85 , '<li>DELETE /users/4</li>'86 , '</ul>'87 ].join('\n')); 88});8990/* istanbul ignore next */91if (!module.parent) {92 app.listen(3000);93 console.log('Express started on port 3000');94}