-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
78 lines (69 loc) · 1.78 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
'use strict'
let Promise = require('promise')
let Hapi = require('hapi')
let http = require('http')
let fs = require('then-fs')
let Routes = require('./routes')
class Api {
constructor (port) {
this._routes = new Set()
this._server = http.createServer()
this._serverListener = Promise.denodeify(this._server.listen)
this.server = new Hapi.Server()
this.serverStart = Promise.denodeify(this.server.start)
this.port = port
this._http = true
this._start()
}
_connection () {
if (this._http) {
this.server.connection({
port: this.port,
labels: ['tcp']
})
}
if (process.env.SOCKET) {
this.server.connection({
listener: this._server,
autoListen: false,
labels: ['socket']
})
}
}
_start () {
this._connection()
if (!process.env.SOCKET) return this._goStart()
fs.unlink(process.env.SOCKET)
.catch(err => { if (err.code !== 'ENOENT') throw err })
.then(this._serverListener.bind(this._server, process.env.SOCKET))
.done(() => this._goStart())
}
_goStart () {
this.server.start(err => {
this._routes.forEach(route => this.server.route(route))
if (err) throw err
console.log('Server LSQ-local API Started')
})
}
addRoute (route) {
if (typeof route !== 'object') return
if (!this._routes.has(route)) return
this._routes.push(route)
if (this._started) {
this.server.route(route)
}
}
addRoutes (routes) {
for (const route in routes) {
if (!this._routes.has(routes[route])) {
this._routes.add(routes[route])
if (this._started) {
this.server.route(routes[route])
}
}
}
}
}
const api = new Api(process.env.PORT || 3000, true)
api.addRoutes(Routes)
module.exports = api