-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
87 lines (74 loc) · 2.7 KB
/
server.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
76
77
78
79
80
81
82
83
84
85
86
87
import * as http from 'http';
import Koa from 'koa';
import cors from '@koa/cors';
import respond from 'koa-respond';
import bodyParser from 'koa-bodyparser';
import compress from 'koa-compress';
import serveStatic from 'koa-static-server';
import { scopePerRequest, loadControllers } from 'awilix-koa';
import path from 'path';
import { logger } from './logger';
import { configureContainer } from './container';
import { notFoundHandler } from '../middleware/not-found';
import { errorHandler } from '../middleware/error-handler';
/** npm
* Creates and returns a new Koa application.
* Does *NOT* call `listen`!
*
* @return {Promise<http.Server>} The configured app.
*/
export async function createServer() {
logger.debug('Creating server...');
const app = new Koa();
// Container is configured with our services and whatnot.
const container = (app.container = await configureContainer());
app
// Top middleware is the error handler.
.use(errorHandler)
// Compress all responses.
.use(compress())
// Adds ctx.ok(), ctx.notFound(), etc..
.use(respond())
// Handles CORS.
.use(cors())
// Parses request bodies.
.use(bodyParser())
.use(
serveStatic({
rootPath: '/demo',
rootDir: path.join(__dirname, '/../../demo')
})
)
.use(
serveStatic({
rootPath: '/images',
rootDir: app.container.resolve('imageDestinationFolder')
})
);
let buildFolder = process.env.NODE_ENV !== ' development' ? '/build' : '';
app.use(
serveStatic({
rootPath: '/web',
rootDir: path.join(__dirname, '/../../frontend', buildFolder),
notFoundFile: 'index.html'
})
);
// Creates an Awilix scope per request. Check out the awilix-koa
// docs for details: https://github.com/jeffijoe/awilix-koa
app.use(scopePerRequest(container));
// Load routes (API "controllers")
app.use(loadControllers('../routes/*.js', { cwd: __dirname }));
// Default handler when nothing stopped the chain.
app.use(notFoundHandler);
// Creates a http server ready to listen.
const server = http.createServer(app.callback());
// Add a `close` event listener so we can clean up resources.
server.on('close', () => {
// You should tear down database connections, TCP connections, etc
// here to make sure Jest's watch-mode some process management
// tool does not release resources.
logger.debug('Server closing, bye!');
});
logger.debug('Server created, ready to listen', { scope: 'startup' });
return server;
}