-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
103 lines (87 loc) · 2.59 KB
/
index.js
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
var log = {};
module['exports'] = log;
var logSubcriberClient;
var MAX_LOGS_PER_HOOK = 50;
var redis = require("redis");
var client;
log.start = function (opts) {
client = redis.createClient(opts.port, opts.host);
if (opts.password !== null) {
client.auth(opts.password);
}
logSubcriberClient = redis.createClient(opts.port, opts.host);
if (opts.password !== null) {
logSubcriberClient.auth(opts.password)
}
// TODO: better error handling and client setup/teardown
client.on("error", function (err) {
console.log("Error: " + err);
});
// TODO: better error handling and client setup/teardown
logSubcriberClient.on("error", function (err) {
console.log("Error: " + err);
});
}
log.flush = function (endpoint, cb) {
client.del("/hook" + endpoint + "/logs", function(err, results){
// show logs in reverse order
return cb(err, results);
});
};
log.recent = function (endpoint, cb) {
// gets the most recent logs for endpoint
client.lrange("/hook" + endpoint + "/logs", 0, MAX_LOGS_PER_HOOK, function (err, results){
// show logs in reverse order
results = results.reverse();
// turn LRANGE entries back into JSON
results = results.map(function (item) {
return JSON.parse(item);
});
return cb(err, results);
});
};
log.stream = function (outputStream){
// tails the most recent log entries for user
};
log.push = function push (endpoint, entry, cb) {
// Before adding a new entry we must check if endpoint has exceeded MAX_LOGS_PER_HOOK
// if so, then pop the last item from the list before adding a new item
log._count("/hook" + endpoint + "/logs", function(err, res){
if (err) {
return cb(err);
}
if (res >= MAX_LOGS_PER_HOOK) {
// console.log("Max log entries hit!");
return removeLastEntry();
} else {
return addEntry();
}
});
function addEntry () {
// add entry to set
client.rpush("/hook" + endpoint + "/logs", JSON.stringify(entry), function (err, res) {
if (err) {
return cb(err);
}
// console.log('attempting to publish', "/hook" + endpoint + "/logs")
logSubcriberClient.publish("/hook" + endpoint + "/logs", JSON.stringify(entry));
});
};
function removeLastEntry () {
client.lpop("/hook" + endpoint + "/logs", function (err, result){
if (err) {
return cb(err);
}
addEntry();
});
};
};
// gets the amount of logs currently keyed to endpoint
log._count = function (endpoint, cb) {
client.llen(endpoint, function (err, res){
if (err) {
return cb(err);
}
cb(null, res);
})
};