-
Notifications
You must be signed in to change notification settings - Fork 741
/
Copy pathapp.js
50 lines (40 loc) · 1.42 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
const compose = require('koa-compose');
const Koa = require('koa');
const app = module.exports = new Koa();
// virtual host apps
const wwwSubdomain = composer(require('./apps/koa'));
const barSubdomain = composer(require('./apps/array'));
// compose koa apps and middleware arrays
// to be used later in our host switch generator
function composer(app) {
const middleware = app instanceof Koa ? app.middleware : app;
return compose(middleware);
}
// look ma, global response logging for all our apps!
app.use(async function(ctx, next) {
const start = new Date();
await next();
const ms = new Date() - start;
if ('test' != process.env.NODE_ENV) {
console.log('%s %s %s - %sms', ctx.host, ctx.method, ctx.url, ms);
}
});
// switch between appropriate hosts calling their
// composed middleware with the appropriate context.
app.use(async function(ctx, next) {
switch (ctx.hostname) {
case 'example.com':
case 'www.example.com':
// displays `Hello from main app`
// and sets a `X-Custom` response header
return await wwwSubdomain.apply(this, [ctx, next]);
case 'bar.example.com':
// displays `Howzit? From bar middleware bundle`
// and sets a `X-Response-Time` response header
return await barSubdomain.apply(this, [ctx, next]);
}
// everything else, eg: 127.0.0.1:3000
// will propagate to 404 Not Found
return await next();
});
if (!module.parent) app.listen(3000);