This repository has been archived by the owner on Jan 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
api
executable file
·76 lines (61 loc) · 1.82 KB
/
api
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/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: 'hmac-sha-256',
user: id
};
return callback(null, credentials);
});
}
options.auth.getCredentialsFunc = credentialsFunc;
// modify default error format
options.format = {
error: function (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);
// don't require authorization for docs (may change after hapi 0.9.2)
server._routes['get'][0].config.auth = config.hapi.docs.auth;
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);
});