UNPKG

1.21 kBJavaScriptView Raw
1'use strict'
2
3const { check } = require('./configuration')
4const dispatcher = require('./dispatcher')
5const EventEmitter = require('events')
6const http = require('http')
7const https = require('https')
8
9function 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
19function 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
26module.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}