1 | 'use strict'
|
2 |
|
3 | const { check } = require('./configuration')
|
4 | const dispatcher = require('./dispatcher')
|
5 | const EventEmitter = require('events')
|
6 | const http = require('http')
|
7 | const https = require('https')
|
8 | const { $configurationInterface } = require('./symbols')
|
9 |
|
10 | function createServer (configuration, requestHandler) {
|
11 | if (configuration.ssl) {
|
12 | return https.createServer({
|
13 | key: configuration.ssl.key,
|
14 | cert: configuration.ssl.cert
|
15 | }, requestHandler)
|
16 | }
|
17 | return http.createServer(requestHandler)
|
18 | }
|
19 |
|
20 | function createServerAsync (eventEmitter, configuration, dispatcher) {
|
21 | return new Promise((resolve, reject) => {
|
22 | const server = createServer(configuration, dispatcher.bind(eventEmitter, configuration))
|
23 | eventEmitter.emit('server-created', { configuration: configuration[$configurationInterface], server })
|
24 | server.listen(configuration.port, configuration.hostname, err => err ? reject(err) : resolve())
|
25 | })
|
26 | }
|
27 |
|
28 | module.exports = jsonConfiguration => {
|
29 | const eventEmitter = new EventEmitter()
|
30 | check(jsonConfiguration)
|
31 | .then(configuration => {
|
32 | configuration.listeners.forEach(register => register(eventEmitter))
|
33 | return createServerAsync(eventEmitter, configuration, dispatcher)
|
34 | .then(() => {
|
35 | eventEmitter.emit('ready', {
|
36 | url: `${configuration.protocol}://${configuration.hostname || '0.0.0.0'}:${configuration.port}/`
|
37 | })
|
38 | })
|
39 | })
|
40 | .catch(reason => eventEmitter.emit('error', { reason }))
|
41 | return eventEmitter
|
42 | }
|