forked from koajs/logger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.js
74 lines (55 loc) · 1.23 KB
/
example.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
var logger = require('./');
var koa = require('koa');
var compress = require('koa-compress')();
var app = koa();
// wrap subsequent middleware in a logger
app.use(logger());
// 204
app.use(function *(next){
if ('/204' == this.path) this.status = 204;
else yield next;
})
// 404
app.use(function *(next){
if ('/404' == this.path) return;
yield next;
})
// destroy
app.use(function *(next){
if ('/close' == this.path) return this.req.destroy();
yield next;
})
// compress the response 1/2 the time to calculate the stream length
app.use(function *(next){
if (Math.random() > 0.5) {
yield next;
} else {
yield compress.call(this, next);
}
})
// response middleware
app.use(function *(next){
// yield control downstream
yield next;
// sleep for 0-2s
yield sleep(Math.random() * 2000 | 0);
// error
if (Math.random() > .75) {
var err = new Error('boom');
err.status = 500;
throw err;
}
// random body
var body = Array(Math.random() * 5 * 1024 | 9).join('a');
this.status = 200;
this.body = body;
});
var port = process.env.PORT || 3000;
app.listen(port);
console.log('listening on port ' + port);
// sleep helper
function sleep(ms) {
return function(done){
setTimeout(done, ms);
}
}