UNPKG

2.41 kBJavaScriptView Raw
1'use strict';
2
3var _isPlainObject = require('lodash/isPlainObject');
4var Util = require('util');
5var FS = require('fs');
6var HTTP = require('http');
7var HTTPS = require('https');
8
9var Log = require('./../core/Log');
10var IConnectionServer = require('./../core/IConnectionServer');
11
12/**
13 *
14 * @class
15 * @implements IConnectionServer
16 *
17 * @param {ServerListener} listener
18 * @param {IFSiteConfig} config
19 */
20function NodeHTTPServer(listener, config) {
21 this._constructor(listener, config);
22}
23
24Util.inherits(NodeHTTPServer, IConnectionServer);
25
26/**
27 *
28 * @param {ServerListener} listener
29 * @param {IFSiteConfig} config
30 */
31NodeHTTPServer.prototype._constructor = function(listener, config) {
32 this._config = config;
33
34 Object.defineProperty(this, 'server', {
35 enumerable: true,
36 value: this._create_server(listener)
37 });
38};
39
40/**
41 *
42 * @param {function} configurator
43 */
44NodeHTTPServer.prototype.configure = function(configurator) {
45 configurator(this.server);
46};
47
48/**
49 *
50 * @param {function} [callback]
51 */
52NodeHTTPServer.prototype.listen = function(callback) {
53 var config = this._config.local;
54 var params = [];
55
56 if(config.port) {
57 params.push(config.port);
58 }
59
60 var host = config.host;
61
62 if(host !== '127.0.0.1' && host !== 'localhost') {
63 params.push(config.host);
64 }
65
66 if(typeof callback === 'function') {
67 params.push(callback);
68 }
69
70 this.server.listen.apply(this.server, params);
71};
72
73/**
74 *
75 * @param {function} [callback]
76 */
77NodeHTTPServer.prototype.close = function(callback) {
78 this.server.close(callback);
79};
80
81/**
82 *
83 * @param {ServerListener} listener
84 * @returns {http.Server}
85 * @private
86 */
87NodeHTTPServer.prototype._create_server = function(listener) {
88 var credentials = this._config.ssl;
89
90 if(!_isPlainObject(credentials)) {
91 return HTTP.createServer(listener);
92 }
93
94 if(credentials.pfx) {
95 credentials = {
96 pfx: FS.readFileSync(credentials.pfx, 'utf8')
97 };
98 } else if(credentials.key && credentials.cert) {
99 credentials = {
100 key: FS.readFileSync(credentials.key, 'utf8'),
101 cert: FS.readFileSync(credentials.cert, 'utf8')
102 };
103 } else {
104 Log.error('extension:ifnode-http', 'Wrong https credentials');
105 }
106
107 return HTTPS.createServer(credentials, listener);
108};
109
110module.exports = NodeHTTPServer;