-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
75 lines (55 loc) · 3.18 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Simple app to explore Node.js + Koa + MySQL basics for CRUD admin + API */
/* */
/* App comprises three (composed) sub-apps: */
/* - www. (public website pages) */
/* - admin. (pages for interactively managing data) */
/* - api. (RESTful CRUD API) */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
'use strict';
const koa = require('koa'); // Koa framework
const body = require('koa-body'); // body parser
const compose = require('koa-compose'); // middleware composer
const compress = require('koa-compress'); // HTTP compression
const responseTime = require('koa-response-time'); // X-Response-Time middleware
const session = require('koa-session'); // session for passport login, flash messages
const mysql = require('mysql-co'); // MySQL (co wrapper for mysql2)
const app = module.exports = koa();
// return Koa response time in X-Response-Time header
app.use(responseTime());
// HTTP compression
app.use(compress({}));
// parse request body into ctx.request.body
app.use(body());
// session for passport login, flash messages
app.keys = ['koa-test-app'];
app.use(session(app));
// MySQL connection pool TODO: how to catch connection exception eg invalid password?
const config = require('./config/db-' + app.env + '.json');
global.connectionPool = mysql.createPool(config.db); // put in global to pass to sub-apps
// select sub-app (admin/api) according to host subdomain (could also be by analysing request.url);
app.use(function* subApp(next) {
// use subdomain to determine which app to serve: www. as default, or admin. or api
const subapp = this.hostname.split('.')[0]; // subdomain = part before first '.' of hostname
switch (subapp) {
case 'admin':
yield compose(require('./apps/admin/app-admin.js').middleware);
break;
case 'api':
yield compose(require('./apps/api/app-api.js').middleware);
break;
case 'www':
yield compose(require('./apps/www/app-www.js').middleware);
break;
default: // no (recognised) subdomain? to www.host
// note switch must include all registered subdomains to avoid potential redirect loop
this.redirect(this.protocol + '://' + 'www.' + this.host + this.path + this.search);
break;
}
});
if (!module.parent) {
app.listen(process.env.PORT||7010);
const db = require('./config/db-' + app.env + '.json').db.database;
console.log(process.version + ' listening on port ' + (process.env.PORT || 7010) + ' (' + app.env + '/' + db + ')');
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */