-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathapp.js
57 lines (49 loc) · 1.52 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
const express = require('express')
, config = require('./config/config')
, fs = require('fs')
, mongoose = require('mongoose')
, log = require('./config/log')()
let isFirstConnect = true
function connect(success, error) {
function onConnectFailed(err) {
setTimeout(() => { error() }, 0)
console.error(err)
throw new Error(`unable to connect to database at ${config.db}`)
}
log.default('Attempting to connect to database ...')
mongoose.set('strictQuery', true)
mongoose.connect(config.db, {
connectTimeoutMS: 3000,
serverSelectionTimeoutMS: 9000,
})
.then(() => {
log.default('Successfully established database connection.')
})
.catch(onConnectFailed)
const db = mongoose.connection
db.on('error', onConnectFailed)
db.on('disconnected', () => console.warn('Database disconnected.'))
db.on('connected', () => {
if (isFirstConnect) {
isFirstConnect = false
return success()
}
console.log('Database reconnected.')
})
}
function run() {
const models = fs.readdirSync(`${config.root}/app/models`).filter((f) => {
return f.endsWith('.js')
})
models.forEach((model) => {
require(`${config.root}/app/models/${model}`)
})
const app = express()
require('./config/express')(app, config)
app.listen(config.port, config.addr, () => {
log.default(`Express server listening on ${config.addr}:${config.port}`)
})
}
connect(run, () => {
process.exit(1)
})