-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
79 lines (63 loc) · 1.95 KB
/
index.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
// provides all API services consumed by VML and VML Admin front ends
require('dotenv').config()
// -------------- Require vendor code -----------------
const Blipp = require('blipp')
const Hapi = require('@hapi/hapi')
const HapiAuthJwt2 = require('hapi-auth-jwt2')
// -------------- Require project code -----------------
const config = require('./config')
const routes = require('./src/routes.js')
const db = require('./src/lib/connectors/db')
const HapiPinoPlugin = require('./src/plugins/hapi-pino.plugin.js')
// Initialise logger
const { logger } = require('./src/logger')
// Define server
const server = Hapi.server(config.server)
const registerServerPlugins = async (server) => {
await server.register(HapiPinoPlugin())
await server.register({
plugin: Blipp,
options: config.blipp
})
// JWT token auth
await server.register(HapiAuthJwt2)
}
const configureServerAuthStrategy = (server) => {
server.auth.strategy('jwt', 'jwt', {
...config.jwt,
validate: async (decoded) => ({ isValid: !!decoded.id })
})
server.auth.default('jwt')
}
const start = async function () {
try {
await registerServerPlugins(server)
configureServerAuthStrategy(server)
server.route(routes)
if (!module.parent) {
await server.start()
const name = process.env.SERVICE_NAME
const uri = server.info.uri
server.log('info', `Service ${name} running at: ${uri}`)
}
} catch (err) {
logger.error(err.stack)
}
}
const processError = message => err => {
logger.error(message, err.stack)
process.exit(1)
}
process
.on('unhandledRejection', processError('unhandledRejection'))
.on('uncaughtException', processError('uncaughtException'))
.on('SIGINT', async () => {
logger.info('Stopping returns service')
await server.stop()
logger.info('1/2: Hapi server stopped')
await db.pool.end()
logger.info('2/2: Connection pool closed')
return process.exit(0)
})
start()
module.exports = server