forked from koajs/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
58 lines (46 loc) · 1.08 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
/**
* Each `app.use()` only accepts a single generator function.
* If you want to combine multiple generator functions into a single one,
* you can use `koa-compose` to do so.
* This allows you to use `app.use()` only once.
* Your code will end up looking something like:
*
* app.use(compose([
* function *(){},
* function *(){},
* function *(){}
* ]))
*/
var compose = require('koa-compose');
var koa = require('koa');
var app = module.exports = koa();
// x-response-time
function *responseTime(next){
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
}
// logger
function* logger(next){
var start = new Date;
yield next;
var ms = new Date - start;
if ('test' != process.env.NODE_ENV) {
console.log('%s %s - %s', this.method, this.url, ms);
}
}
// response
function* respond(next){
yield next;
if ('/' != this.url) return;
this.body = 'Hello World';
}
// composed middleware
var all = compose([
responseTime,
logger,
respond
]);
app.use(all);
if (!module.parent) app.listen(3000);