-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
96 lines (91 loc) · 2.75 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/* global Promise */
global.Promise = require('bluebird')
const http = require('http')
const cors = require('cors')
const helmet = require('helmet')
const express = require('express')
const bodyParser = require('body-parser')
const status = require('http-status')
const config = require('./config')
const logger = require('./utils/logger')
const util = require('./utils/util')
const errors = require('./utils/errors')
const ApiError = require('./utils/api-error')
const response = require('./utils/response')
const fs = require('fs')
const path = require('path')
const _ = require('lodash')
const setupRoutes = require('././libs/routes')
const exitProcess = () => setTimeout(() => process.exit(1), 100)
/** Global process events */
Promise.onPossiblyUnhandledRejection(async (error) => {
await util.traceError(error)
exitProcess()
})
process.on('uncaughtException', async (error) => {
await util.traceError(error)
exitProcess()
})
process.on('unhandledRejection', async (error) => {
await util.traceError(error)
exitProcess()
})
const start = async () => {
try {
logger.info('[Server] Initializing application')
const app = express()
app.server = http.createServer(app)
// REGISTER
app.use(cors())
app.use(helmet({
dnsPrefetchControl: false,
frameguard: false,
ieNoOpen: false
}))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// LOG REQUEST
app.use((req, res, next) => {
const clientIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress
const { originalUrl, method } = req
logger.info(`[Server] ${clientIp} | ${method}: ${originalUrl}`)
if (method.toUpperCase() !== 'GET') logger.debug(`[Server] Body: ${JSON.stringify(req.body)}`)
next()
})
// STATICS
app.use('/uploads', express.static(path.join(__dirname, 'uploads')))
// DATABASE
const dbService = require('././libs/db')
await dbService.authenticate()
process.on('SIGINT', async () => {
await dbService.close()
exitProcess()
})
// ROUTES
setupRoutes(app)
// NOT FOUND
app.use((req, res) => response(res).error(new ApiError('Api not found', status.NOT_FOUND)))
// ERROR HANDLING
app.use(errors.middleware)
app.use((err, req, res, next) => {
response(res).error(err)
if (req.file) {
fs.unlinkSync(req.file.path)
}
if (req.files) {
const uploaded = _.flattenDeep(req.files)
uploaded.forEach((file) => fs.unlinkSync(file.path))
}
util.traceError(err)
})
app.server.listen(config.port, () => {
logger.info(`[Server] Listening on port ${app.server.address().port}`)
})
} catch (e) {
util.traceError(e)
exitProcess()
}
}
module.exports = {
start
}