-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
88 lines (72 loc) · 2.42 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
80
81
82
83
84
85
86
87
88
require('dotenv').config()
const config = require('config')
const debug = require('debug')('app:index.js')
const express = require('express')
const mongoose = require('mongoose')
const open = require('open')
require('express-async-errors')
const errorMiddleware = require('middleware/error.middleware')
const middleware = require('middleware/middleware')
const preloadModels = require('models/preloadModels')
const routes = require('routes/routes')
const cli = require('utils/cli')
const createServer = require('utils/createServer')
const asyncHandler = require('utils/factories/asyncError')
const setupPassport = require('utils/passport/setupPassport')
const reportError = require('utils/reportError')(debug)
const { isFunction } = require('utils/utils')
const app = express()
const server = createServer(app)
const DB = config.get('mongodb.db')
const PORT = config.get('port')
const stop = (...args) => {
debug(`${args.join(' ')}`)
if (isFunction(mongoose?.disconnect)) mongoose.disconnect()
if (isFunction(server?.close)) server.close()
}
const start = () => {
asyncHandler(async () => {
// connect to database
await mongoose.connect(DB, {
...config.get('mongodb.options'),
...config.get('mongoose'),
})
preloadModels()
setupPassport()
// Required middlewares
app.use(middleware())
// Api Routes
app.use('/api', routes)
// Ping
app.use('/ping', (req, res) => res.send('pong'))
// Error handling middleware
app.use(errorMiddleware)
// Redirect to frontend located in 'public/'
app.get(express.static('./public'))
app.get('*', (req, res) => res.sendFile('index.html', { root: './public' }))
// Start listening to requests
server.listen(config.get('port'))
})
}
mongoose.connection
.on('connected', () => debug(cli.messages.databaseConnected(DB)))
.on('disconnected', () => debug(cli.messages.databaseDisconnected(DB)))
server
.on('listening', () => debug(cli.messages.serverListening(PORT)))
.on('close', () => debug(cli.messages.serverClosed(PORT)))
process
.on('SIGHUP', stop)
.on('SIGINT', stop)
.on('SIGTERM', stop)
.on('beforeExit', stop)
.on('uncaughtException', reportError)
.on('unhandledRejection', reportError)
if (config.get('env') === 'development') {
if (process.env.INIT === '0') {
server.on('listening', () => {
// Serve openapi docs in browser
open(`${config.get('publicUrl')}/api/docs`)
})
}
}
start()