-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
58 lines (50 loc) · 1.78 KB
/
server.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
// import 'dotenv/config'
import express from 'express'
import router from './server/routes/api'
import mongoose from 'mongoose'
import path from 'path'
import cors from 'cors'
import { exit } from 'process'
(async () => {
const app = express()
app.use(cors())
if (! (process.env.MONGODB_URI || process.env.PORT) ){
exit()
}
const PORT = process.env.PORT
const DBname = "CV-Pdf"
const MONGO_URL = process.env.MONGODB_URI || `mongodb://localhost/${DBname}`
const connection = await mongoose
.connect(MONGO_URL, {
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false
})
.catch(err => {
console.error('Error connecting db:', err.message)
process.env.notDBconnection = true
exit()
})
app.get('/health', (req, res) => res.json({ UP: !!connection }))
if (!connection) {
app.use((req, res) => {
res.status(500)
res.json({ error: 'Server is unavailable at the moment' })
console.error('Server is unavailable at the moment')
})
}
else {
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
next()
})
app.use(express.static(path.join(__dirname, 'build')))
app.use('/', router)
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'))
})
app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`))
}
})()