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 http2 = require('http2')
|
9 | const {
|
10 | $configurationEventEmitter,
|
11 | $configurationInterface
|
12 | } = require('./symbols')
|
13 |
|
14 | function createServer (configuration, requestHandler) {
|
15 | const { httpOptions } = configuration
|
16 | if (configuration.ssl) {
|
17 | if (configuration.http2) {
|
18 | return http2.createSecureServer({
|
19 | key: configuration.ssl.key,
|
20 | cert: configuration.ssl.cert,
|
21 | ...httpOptions
|
22 | }, requestHandler)
|
23 | }
|
24 | return https.createServer({
|
25 | key: configuration.ssl.key,
|
26 | cert: configuration.ssl.cert,
|
27 | ...httpOptions
|
28 | }, requestHandler)
|
29 | }
|
30 | if (configuration.http2) {
|
31 | return http2.createServer(httpOptions, requestHandler)
|
32 | }
|
33 | return http.createServer(httpOptions, requestHandler)
|
34 | }
|
35 |
|
36 | function createServerAsync (eventEmitter, configuration, dispatcher) {
|
37 | return new Promise((resolve, reject) => {
|
38 | const server = createServer(configuration, dispatcher.bind(eventEmitter, configuration))
|
39 | eventEmitter.emit('server-created', { configuration: configuration[$configurationInterface], server })
|
40 | let { port } = configuration
|
41 | if (port === 'auto') {
|
42 | port = 0
|
43 | }
|
44 | server.listen(port, configuration.hostname, err => err ? reject(err) : resolve(server))
|
45 | })
|
46 | }
|
47 |
|
48 | module.exports = jsonConfiguration => {
|
49 | const eventEmitter = new EventEmitter()
|
50 | check(jsonConfiguration)
|
51 | .then(configuration => {
|
52 | configuration[$configurationEventEmitter] = eventEmitter
|
53 | configuration.listeners.forEach(register => register(eventEmitter))
|
54 | return createServerAsync(eventEmitter, configuration, dispatcher)
|
55 | .then(server => {
|
56 | const port = server.address().port
|
57 | const { http2 } = configuration
|
58 | eventEmitter.emit('ready', {
|
59 | url: `${configuration.protocol}://${configuration.hostname || '0.0.0.0'}:${port}/`,
|
60 | port,
|
61 | http2
|
62 | })
|
63 | })
|
64 | })
|
65 | .catch(reason => eventEmitter.emit('error', { reason }))
|
66 | return eventEmitter
|
67 | }
|