forked from expressjs/express
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.param.js
99 lines (82 loc) · 2.3 KB
/
app.param.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var express = require('../')
, request = require('./support/http');
describe('app', function(){
describe('.param(fn)', function(){
it('should map app.param(name, ...) logic', function(done){
var app = express();
app.param(function(name, regexp){
if (Object.prototype.toString.call(regexp) == '[object RegExp]') { // See #1557
return function(req, res, next, val){
var captures;
if (captures = regexp.exec(String(val))) {
req.params[name] = captures[1];
next();
} else {
next('route');
}
}
}
})
app.param(':name', /^([a-zA-Z]+)$/);
app.get('/user/:name', function(req, res){
res.send(req.params.name);
});
request(app)
.get('/user/tj')
.end(function(err, res){
res.text.should.equal('tj');
request(app)
.get('/user/123')
.expect(404, done);
});
})
})
describe('.param(names, fn)', function(){
it('should map the array', function(done){
var app = express();
app.param(['id', 'uid'], function(req, res, next, id){
id = Number(id);
if (isNaN(id)) return next('route');
req.params.id = id;
next();
});
app.get('/post/:id', function(req, res){
var id = req.params.id;
id.should.be.a.Number;
res.send('' + id);
});
app.get('/user/:uid', function(req, res){
var id = req.params.id;
id.should.be.a.Number;
res.send('' + id);
});
request(app)
.get('/user/123')
.end(function(err, res){
res.text.should.equal('123');
request(app)
.get('/post/123')
.expect('123', done);
})
})
})
describe('.param(name, fn)', function(){
it('should map logic for a single param', function(done){
var app = express();
app.param('id', function(req, res, next, id){
id = Number(id);
if (isNaN(id)) return next('route');
req.params.id = id;
next();
});
app.get('/user/:id', function(req, res){
var id = req.params.id;
id.should.be.a.Number;
res.send('' + id);
});
request(app)
.get('/user/123')
.expect('123', done);
})
})
})