UNPKG

1.51 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 server.listen(configuration.port, configuration.hostname, err => err ? reject(err) : resolve())
25 })
26}
27
28module.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}