Repository navigation
Expand file tree
/
Copy pathhooks.js
More file actions
88 lines (74 loc) · 2.08 KB
/
Copy pathhooks.js
File metadata and controls
88 lines (74 loc) · 2.08 KB
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
77
78
79
80
81
82
83
84
85
86
87
var Q = require('q');
var _ = require('lodash');
var request = require('request');
var logger = require("./utils/logger")("hooks");
var BOXID = null;
var HOOKS = {};
var POSTHOOKS = {
'users.auth': function(data) {
// Valid data
if (!_.has(data, "id") || !_.has(data, "name")
|| !_.has(data, "token") || !_.has(data, "email")) {
throw "Invalid authentication data";
}
return data;
}
};
var SECRET_TOKEN = null;
// Call hook
var use = function(hook, data) {
logger.log("call hook ", hook);
if (!HOOKS[hook]) return Q.reject("Hook '"+hook+"' doesn't exists");
return Q()
.then(function() {
var handler = HOOKS[hook];
if (_.isFunction(handler)) {
return Q(handler(data));
} else if (_.isString(handler)) {
var d = Q.defer();
// Do http requests
request.post(handler, {
'body': {
'id': BOXID,
'data': data,
'hook': hook
},
'headers': {
'Authorization': SECRET_TOKEN
},
'json': true,
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
d.resolve(body);
} else {
d.reject(new Error("Error with "+hook+" webhook: "+(body ? (body.error || body) : error.message)));
}
});
return d.promise;
} else {
throw "Not a valid hook";
}
})
.then(function(data) {
if (POSTHOOKS[hook]) {
return POSTHOOKS[hook](data);
}
return data;
})
.fail(function(err) {
logger.error("Error with hook:");
logger.exception(err, false);
return Q.reject(err);
});
};
// Init hook system
var init = function(options) {
logger.log("init hooks");
BOXID = options.id;
HOOKS = options.hooks;
SECRET_TOKEN = options.secret;
};
module.exports = {
init: init,
use: use
};