UNPKG

1.64 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')
8const { $configurationInterface } = require('./symbols')
9
10function 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
20function 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 let { port } = configuration
25 if (port === 'auto') {
26 port = 0
27 }
28 server.listen(port, configuration.hostname, err => err ? reject(err) : resolve(server))
29 })
30}
31
32module.exports = jsonConfiguration => {
33 const eventEmitter = new EventEmitter()
34 check(jsonConfiguration)
35 .then(configuration => {
36 configuration.listeners.forEach(register => register(eventEmitter))
37 return createServerAsync(eventEmitter, configuration, dispatcher)
38 .then(server => {
39 const port = server.address().port
40 eventEmitter.emit('ready', {
41 url: `${configuration.protocol}://${configuration.hostname || '0.0.0.0'}:${port}/`,
42 port
43 })
44 })
45 })
46 .catch(reason => eventEmitter.emit('error', { reason }))
47 return eventEmitter
48}