-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
86 lines (75 loc) · 1.94 KB
/
server.js
File metadata and controls
86 lines (75 loc) · 1.94 KB
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
import Bluebird from 'bluebird'
import Boom from '@hapi/boom'
import * as Hoek from '@hapi/hoek'
import Glue from '@hapi/glue'
import Config from './config/index.js'
import __dirname from './utils/path.js'
global.Promise = Bluebird
/**
* @type {import('@hapi/hapi').Server | {}}
*/
let hapiServer = {}
const server = {}
// default value
const defaultManifest = {
server: {
port: Config.server.port,
host: Config.server.host,
routes: {
cors: { origin: Config.server.allowOrigins },
validate: {
/**
*
* @param {import('@hapi/hapi').Request & {server: {boom: import('@hapi/boom')}}} request
* @param {import('@hapi/hapi').ResponseToolkit} h
* @param {Error} err
*/
failAction: (request, h, err) => {
if (Config.environment === 'dev') {
console.log({
tag: '[VALIDATION_ERROR]',
err
})
throw err
}
// to protect the validation message from outsiders
throw Boom.badRequest()
}
}
}
}
}
const defaultOptions = {
relativeTo: __dirname
}
server.configure = (manifest = {}, options = {}) => {
server.manifest = Hoek.applyToDefaults(defaultManifest, manifest)
server.options = Hoek.applyToDefaults(defaultOptions, options)
return server
}
server.start = async () => {
hapiServer = await Glue.compose(server.manifest, server.options)
await hapiServer.start()
console.log({
tag: '[SERVER_STARTED]',
time: new Date().toUTCString()
})
}
process.on('SIGINT', async () => {
// close all necessary connection here
await hapiServer.stop({ timeout: 5000 })
console.log({
tag: '[SERVER_STOPPED]',
time: new Date().toUTCString()
})
process.exit(0)
})
process.on('unhandledRejection', (err) => {
console.error({
tag: '[SERVER_UNHANDLED_REJECTION]',
err
})
process.exit(1)
})
server.getInstance = () => hapiServer
export default server