forked from expressjs/express
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
69 lines (55 loc) · 1.21 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Module dependencies.
*/
var express = require('../../');
var app = module.exports = express();
// Faux database
var users = [
{ name: 'tj' }
, { name: 'tobi' }
, { name: 'loki' }
, { name: 'jane' }
, { name: 'bandit' }
];
// Convert :to and :from to integers
app.param(['to', 'from'], function(req, res, next, num, name){
req.params[name] = num = parseInt(num, 10);
if( isNaN(num) ){
next(new Error('failed to parseInt '+num));
} else {
next();
}
});
// Load user by id
app.param('user', function(req, res, next, id){
if (req.user = users[id]) {
next();
} else {
next(new Error('failed to find user'));
}
});
/**
* GET index.
*/
app.get('/', function(req, res){
res.send('Visit /user/0 or /users/0-2');
});
/**
* GET :user.
*/
app.get('/user/:user', function(req, res, next){
res.send('user ' + req.user.name);
});
/**
* GET users :from - :to.
*/
app.get('/users/:from-:to', function(req, res, next){
var from = req.params.from;
var to = req.params.to;
var names = users.map(function(user){ return user.name; });
res.send('users ' + names.slice(from, to).join(', '));
});
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
}