UNPKG

2.49 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 params.push(config.port ?
57 config.port :
58 0
59 );
60
61 var host = config.host;
62
63 if(host !== '127.0.0.1' && host !== 'localhost') {
64 params.push(config.host);
65 }
66
67 if(typeof callback === 'function') {
68 params.push(callback);
69 }
70
71 this.server.listen.apply(this.server, params);
72};
73
74/**
75 *
76 * @param {function} [callback]
77 */
78NodeHTTPServer.prototype.close = function(callback) {
79 this.server.close(callback);
80};
81
82/**
83 *
84 * @param {ServerListener} listener
85 * @returns {http.Server}
86 * @private
87 */
88NodeHTTPServer.prototype._create_server = function(listener) {
89 var credentials = this._config.ssl;
90
91 if(!_isPlainObject(credentials)) {
92 return HTTP.createServer(listener);
93 }
94
95 if(credentials.pfx) {
96 credentials = {
97 pfx: FS.readFileSync(credentials.pfx),
98 passphrase: credentials.passphrase
99 };
100 } else if(credentials.key && credentials.cert) {
101 credentials = {
102 key: FS.readFileSync(credentials.key),
103 cert: FS.readFileSync(credentials.cert),
104 passphrase: credentials.passphrase
105 };
106 } else {
107 Log.error('extension:ifnode-http', 'Wrong https credentials');
108 }
109
110 return HTTPS.createServer(credentials, listener);
111};
112
113module.exports = NodeHTTPServer;