-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
83 lines (65 loc) · 1.8 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
76
77
const path = require('path')
const Koa = require('koa')
const Router = require('koa-router')
const body = require('koa-body')
const helmet = require('koa-helmet')
const cors = require('kcors')
const swagger = require('swagger2')
const swagger_router = require('swagger2-koa').router
const swagger_validate = require('swagger2-koa').validate
const swagger_ui = require('swagger2-koa').ui
const package = require(path.join(__dirname, "package.json"))
const config = require(path.join(__dirname, "config"))
const bootstrap = require(path.join(__dirname, "config/bootstrap.js"))
var app = new Koa()
//CORS
app.use(cors())
//Security
app.use(helmet())
//Body Parser
app.use(body())
// Swagger - UI
const document = swagger.loadDocumentSync(__dirname + '/swagger.yml')
app.use(swagger_ui(document, "/docs"))
//Swagger - validate
if (!swagger.validateDocument(document)) {
throw Error(`./swagger.yml does not conform to the Swagger 2.0 schema`)
}
app.use(swagger_validate(document))
//Simple Log
app.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.request.ip} -> ${ctx.method} ${ctx.url} - ${ms}ms`)
})
//Error Handler
app.use(async (ctx, next) => {
try {
await next()
} catch (err) {
ctx.status = err.statusCode || err.status || 500
console.log(`Error Response: Code=${ctx.status}, Message=${err.message}`)
if(ctx.status == 500) {
console.error(err)
}
}
});
//Start Server
var serve = async () => {
try {
await bootstrap(app, config)
return app.listen(config.port, () => {
console.log(config)
console.info(`Server "${package.name} v${package.version}" started, listening on port ${config.port}...`)
})
} catch(err) {
console.error(err)
process.exit(1)
}
}
if(config.env == 'test') {
module.exports = serve
} else {
serve()
}