-
Notifications
You must be signed in to change notification settings - Fork 59
/
server.js
61 lines (55 loc) · 2.06 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
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 { scopePerRequest, loadControllers } from 'awilix-koa'
import { logger } from './logger'
import { configureContainer } from './container'
import { notFoundHandler } from '../middleware/not-found'
import { errorHandler } from '../middleware/error-handler'
import { registerContext } from '../middleware/register-context'
/**
* 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 = 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())
// Creates an Awilix scope per request. Check out the awilix-koa
// docs for details: https://github.com/jeffijoe/awilix-koa
.use(scopePerRequest(container))
// Create a middleware to add request-specific data to the scope.
.use(registerContext)
// Load routes (API "controllers")
.use(loadControllers('../routes/*.js', { cwd: __dirname }))
// Default handler when nothing stopped the chain.
.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
}