-
Notifications
You must be signed in to change notification settings - Fork 14.2k
/
index.js
80 lines (63 loc) · 1.41 KB
/
index.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
70
71
72
73
74
75
76
77
78
79
80
'use strict'
/**
* Module dependencies.
*/
var express = require('../../');
var app = module.exports = express();
// Faux database
var users = [
{ name: 'tj' }
, { name: 'tobi' }
, { name: 'loki' }
, { name: 'jane' }
, { name: 'bandit' }
];
// Create HTTP error
function createError(status, message) {
var err = new Error(message);
err.status = status;
return err;
}
// Convert :to and :from to integers
app.param(['to', 'from'], function(req, res, next, num, name){
req.params[name] = parseInt(num, 10);
if( isNaN(req.params[name]) ){
next(createError(400, '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(createError(404, '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 + 1).join(', '));
});
/* istanbul ignore next */
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
}