forked from unlock-protocol/unlock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
66 lines (58 loc) · 1.58 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
/* eslint no-console: 0 */
console.log('Starting Locksmith...')
const args = require('yargs').argv
const net = require('net')
const listEndpoints = require('express-list-endpoints')
const app = require('./src/app')
const config = require('./config/config')
const port = process.env.PORT || 8080
const databasePort = 5432
/**
* This is a helper function to ensure that we start the test suite only when the server is up
* We will retry for
*/
const serverIsUp = (host, port, delay, maxAttempts, callback) => {
let attempts = 1
const tryConnecting = () => {
const socket = net.connect(port, host, () => {
callback(null)
return socket.end() // clean-up
})
socket.on('error', (error) => {
if (error.code === 'ECONNREFUSED') {
if (attempts < maxAttempts) {
attempts += 1
return setTimeout(tryConnecting, delay)
}
return callback(error)
}
return callback(error)
})
}
tryConnecting()
}
if (!config.host || process.env.NODE_ENV === 'production') {
console.log(`Listening on ${port}`)
return app.listen(port)
}
if (args.routes) {
console.log('Routes:')
listEndpoints(app).forEach((endpoint) => {
endpoint.methods.forEach((method) => {
console.log(
`${method.padStart(6)} ${endpoint.path.padEnd(56)} => ${
endpoint.middleware
}`
)
})
})
return
}
// We wait for the db server to be up before starting the app
serverIsUp(config.host, databasePort, 100, 120, (error) => {
if (error) {
console.error(error)
return process.exit(1)
}
app.listen(port)
})