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 |
|
9 | function createServer (configuration, requestHandler) {
|
10 | if (configuration.ssl) {
|
11 | return https.createServer({
|
12 | key: configuration.ssl.key,
|
13 | cert: configuration.ssl.cert
|
14 | }, requestHandler)
|
15 | }
|
16 | return http.createServer(requestHandler)
|
17 | }
|
18 |
|
19 | function createServerAsync (configuration, requestHandler) {
|
20 | return new Promise((resolve, reject) => {
|
21 | createServer(configuration, requestHandler)
|
22 | .listen(configuration.port, configuration.hostname, err => err ? reject(err) : resolve())
|
23 | })
|
24 | }
|
25 |
|
26 | module.exports = jsonConfiguration => {
|
27 | const eventEmitter = new EventEmitter()
|
28 | check(jsonConfiguration)
|
29 | .then(configuration => createServerAsync(configuration, dispatcher.bind(eventEmitter, configuration))
|
30 | .then(() => {
|
31 | eventEmitter.emit('ready', {
|
32 | url: `${configuration.protocol}://${configuration.hostname || '0.0.0.0'}:${configuration.port}/`
|
33 | })
|
34 | })
|
35 | )
|
36 | .catch(reason => eventEmitter.emit('error', { reason }))
|
37 | return eventEmitter
|
38 | }
|