embark-area-51/lib/modules/webserver/index.js

68 lines
1.9 KiB
JavaScript
Raw Normal View History

var {canonicalHost} = require('../../utils/host.js');
2017-12-18 14:37:16 +00:00
var utils = require('../../utils/utils.js');
var Server = require('./server.js');
class WebServer {
constructor(embark, options) {
2017-12-29 23:29:56 +00:00
this.embark = embark;
2017-12-18 14:37:16 +00:00
this.logger = embark.logger;
this.events = embark.events;
2017-12-19 14:50:29 +00:00
this.webServerConfig = embark.config.webServerConfig;
if (!this.webServerConfig.enabled) {
2017-12-18 14:37:16 +00:00
return;
}
2017-12-19 14:50:29 +00:00
this.host = options.host || this.webServerConfig.host;
this.port = options.port || this.webServerConfig.port;
2017-12-18 14:37:16 +00:00
2018-05-08 21:49:46 +00:00
this.events.emit("status", __("Starting Server"));
2017-12-19 14:50:29 +00:00
this.server = new Server({logger: this.logger, host: this.host, port: this.port});
this.setServiceCheck();
this.listenToCommands();
2017-12-29 23:29:56 +00:00
this.registerConsoleCommands();
2017-12-19 14:50:29 +00:00
this.server.start();
}
setServiceCheck() {
let url = 'http://' + canonicalHost(this.host) + ':' + this.port;
2017-12-18 14:37:16 +00:00
this.events.request("services:register", 'Webserver', function (cb) {
2017-12-19 14:50:29 +00:00
utils.checkIsAvailable(url, function (available) {
2018-05-08 21:49:46 +00:00
let devServer = __('Webserver') + ' (' + url + ')';
2017-12-19 14:50:29 +00:00
let serverStatus = (available ? 'on' : 'off');
return cb({name: devServer, status: serverStatus});
2017-12-18 14:37:16 +00:00
});
});
2017-12-19 14:50:29 +00:00
this.events.on('check:wentOffline:Webserver', () => {
2018-05-08 21:49:46 +00:00
this.logger.info(__("Webserver is offline"));
2017-12-18 14:37:16 +00:00
});
2017-12-19 14:50:29 +00:00
}
2017-12-18 14:37:16 +00:00
2017-12-19 14:50:29 +00:00
listenToCommands() {
2017-12-19 14:54:39 +00:00
this.events.setCommandHandler('start-webserver', () => { this.server.start(); });
this.events.setCommandHandler('stop-webserver', () => { this.server.stop(); });
2017-12-18 14:37:16 +00:00
}
2017-12-29 23:29:56 +00:00
registerConsoleCommands() {
const self = this;
2017-12-29 23:33:11 +00:00
self.embark.registerConsoleCommand((cmd, _options) => {
2017-12-29 23:29:56 +00:00
if (cmd === 'webserver start') {
self.events.request("start-webserver");
return " ";
}
if (cmd === 'webserver stop') {
self.events.request("stop-webserver");
2018-05-08 21:49:46 +00:00
return __("stopping webserver") + "...";
2017-12-29 23:29:56 +00:00
}
return false;
});
}
2017-12-18 14:37:16 +00:00
}
module.exports = WebServer;