slack-command-server/app.js

74 lines
1.9 KiB
JavaScript
Raw Normal View History

2014-08-09 06:21:11 +00:00
var connect = require('connect'),
SlackIncoming = require('slack-command-router'),
path = require('path'),
2014-08-09 06:40:38 +00:00
fs = require('fs'),
_ = require('lodash');
2014-08-09 06:21:11 +00:00
2014-08-09 06:40:38 +00:00
var config = JSON.parse(fs.readFileSync("config.json"));
var requiredSetup = ["port"];
if (_.intersection(_.keys(config), requiredSetup).length !== requiredSetup.length) {
throw {
message: "Missing required configuration parameters"
}
}
var slack = new SlackIncoming();
2014-08-09 06:21:11 +00:00
var pluginsToInstall = config.plugins || [],
pluginsToLoad = config["local-plugins"] || [];
function installPlugins(callback) {
if (pluginsToInstall.length === 0) {
callback([]);
return;
}
var npm = require('npm');
npm.load({}, function (err) {
if (err) throw err;
npm.commands["install"](pluginsToInstall, function (err) {
if (err) throw err;
var loadedPlugins = [];
for (var i = 0; i < pluginsToInstall.length; i++) {
2014-08-09 06:48:02 +00:00
loadedPlugins.push(require(pluginsToInstall[i]));
2014-08-09 06:21:11 +00:00
}
callback(loadedPlugins);
});
});
}
function loadPlugins(callback) {
var loadedPlugins = [];
for (var i = 0; i < pluginsToLoad.length; i++) {
2014-08-09 06:48:02 +00:00
loadedPlugins.push(require(path.resolve(__dirname, pluginsToLoad[i])));
2014-08-09 06:21:11 +00:00
}
callback(loadedPlugins);
}
function initPlugins(plugins, callback) {
for (var i = 0; i < plugins.length; i++) {
slack.registerHandler(plugins[i]);
}
callback();
}
function initCallback(callback) {
return function (loadedPlugins) {
initPlugins(loadedPlugins, callback);
}
}
function startApp() {
var app = connect();
app.use(slack.getMiddleware());
app.use(function (req, res) {
res.writeHead(400);
res.end("Unable to handle request");
});
2014-08-09 06:40:38 +00:00
app.listen(config.port);
2014-08-09 06:21:11 +00:00
}
installPlugins(initCallback(function() {
loadPlugins(initCallback(startApp));
}));