-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
76 lines (61 loc) · 1.91 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const fs = require('fs')
const express = require('express')
const bodyParser = require('body-parser')
const serveStatic = require('serve-static')
const path = require('path')
const basicAuth = require('express-basic-auth')
const cors = require('cors')
const mongodoc = require('./api/adaptors/mongodoc/mongodocAdaptor')
const api = require('./api/api')
const errors = require('./api/errors')
const port = process.env.PORT || 8000
const authUser = process.env.AUTHUSER || null
const authPass = process.env.AUTHPASS || null
const connectionString = process.env.MONGO
const collectionName = process.env.COLLECTION_NAME || 'structure'
const app = express()
app.use(bodyParser.json())
app.use(cors())
if (authUser && authPass) {
const auth = { users: {}, challenge: true }
auth.users[authUser] = authPass
app.use(basicAuth(auth))
}
const haveConnectionDetails = !!process.env.MONGO
const haveBuildDirectory = fs.existsSync(path.join(__dirname, 'build/index.html'))
const exportables = {
app,
server: null,
go: null,
dataSource: null
}
const go = async () => {
const noGoErrors = []
if (!haveConnectionDetails) {
noGoErrors.push(errors.MONGO_ERROR)
}
if (noGoErrors.length) {
throw(new Error(noGoErrors))
}
exportables.dataSource = await mongodoc({ connectionString, collectionName })
api(app, exportables.dataSource)
console.log('API STARTED')
if (haveBuildDirectory) {
console.log('BUILD DIRECTORY BEING SERVED')
app.use(serveStatic('build/', { index: ['index.html'] }))
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build/index.html'))
})
}
}
exportables.go = go()
.catch(e => {
errors.log(e.message.split())
})
.finally(() => {
app.get('/api/*', (req, res) => res.status(500).send('Error - check config'))
exportables.server = app.listen(port, () => {
console.log('Magic happens on port ' + port)
})
})
module.exports = exportables