gombot/bin/api

80 строки
1.9 KiB
JavaScript
Executable File

#!/usr/bin/env node
// This is the gombot API server!
const Hapi = require('hapi');
const apiLoader = require('../lib/api_loader.js');
const db = require('../lib/db.js');
const config = require('../etc/config');
// Listen to log events
Hapi.Log.on('log', function (event) {
// Send to console
Hapi.Log.print(event);
});
function fatal(msg) {
process.stderr.write("fatal error: " + msg + "\n");
process.exit(1);
}
var options = config.hapi;
// retrieve authKey of user to validate authorized requests
function credentialsFunc(id, callback) {
db.getAuthKey(id, function (err, key){
if (err) return callback(err);
var credentials = {
id: id,
key: new Buffer(key, 'base64'),
algorithm: 'sha256',
user: id
};
return callback(null, credentials);
});
}
options.auth.getCredentialsFunc = credentialsFunc;
// modify default error format
options.format = {
error: function (result) {
console.error('Error: ', result);
return {
code: result.code,
payload: { success: false, errorCode: result.code, errorMessage: result.message },
type: 'application/json'
};
}
};
// Create a server with a host and port
var bindTo = config.process.api;
var server = new Hapi.Server(bindTo.host, bindTo.port, options);
if (config.hapi.docs) {
server.addRoute({ method: 'GET', path: '/api/docs', handler: { docs: true }, config: { auth: { mode: 'none' } } });
}
console.log("api starting up");
// now load up api handlers
apiLoader(server, function(err) {
if (err) fatal(err);
db.connect(config.db, function() {
// Start the server
server.start(function() {
console.log("running on http://" + server.settings.host + ":" + server.settings.port);
});
});
});
process.on('SIGTERM', function() {
server.stop();
// db won't close unless exit called explicitly
process.exit(0);
});