forked from koajs/logger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.js
More file actions
74 lines (57 loc) · 1.34 KB
/
example.js
File metadata and controls
74 lines (57 loc) · 1.34 KB
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
const logger = require('./')
const Koa = require('koa')
const compress = require('koa-compress')()
const app = new Koa()
// wrap subsequent middleware in a logger
app.use(logger())
// 204
app.use(function (ctx, next) {
if (ctx.path === '/204') ctx.status = 204
else return next()
})
// 404
app.use(function (ctx, next) {
if (ctx.path === '/404') return
return next()
})
// destroy
app.use(function (ctx, next) {
if (ctx.path === '/close') return ctx.req.destroy()
return next()
})
// compress the response 1/2 the time to calculate the stream length
app.use(function (ctx, next) {
if (Math.random() > 0.5) {
return next()
} else {
return compress(ctx, next)
}
})
// response middleware
app.use(function (ctx, next) {
// yield control downstream
next().then(function () {
// sleep for 0-2s
return sleep(Math.random() * 2000 | 0)
}).then(function () {
// error
if (Math.random() > 0.75) {
const err = new Error('boom')
err.status = 500
throw err
}
// random body
const body = Array(Math.random() * 5 * 1024 | 9).join('a')
ctx.status = 200
ctx.body = body
})
})
const port = process.env.PORT || 3000
app.listen(port)
console.log('listening on port ' + port)
// sleep helper
function sleep (ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms)
})
}