-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (67 loc) · 1.92 KB
/
index.js
File metadata and controls
69 lines (67 loc) · 1.92 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
const defaults = {
verbose: false,
interval: 1000 * 60, // report rate in milliseconds
threshold: 0.5 // threshold percent beyond which to report
};
const register = (server, passedOptions) => {
const options = {};
// if no methods use cache, then there is no need to run a loop monitoring them:
let cachesExist = false;
Object.assign(options, defaults, passedOptions);
const logMethod = (methodName, method) => {
const stats = method.cache.stats;
if (stats.hits === 0 && stats.gets === 0 && stats.stales === 0) {
return;
}
const logOutput = {
hitRatio: stats.hits / stats.gets,
staleRatio: stats.stales / stats.gets
};
Object.assign(logOutput, method.cache.stats);
if (options.verbose) {
server.log(['hapi-cache-stats', methodName], logOutput);
}
if (logOutput.hitRatio < options.threshold) {
server.log(['hapi-cache-stats', methodName, 'warning'], `Hit ratio of ${logOutput.hitRatio} is lower than threshold of ${options.threshold}`);
}
};
const logObject = (object, prefix) => {
Object.keys(object).forEach((key) => {
const method = object[key];
const logKey = prefix ? `${prefix}.${key}` : key;
if (typeof method === 'object') {
logObject(method, logKey);
}
if (typeof method === 'function') {
if (method.cache) {
cachesExist = true;
logMethod(logKey, method);
}
}
});
};
let currentTimer;
const onTimer = () => {
cachesExist = false;
logObject(server.methods);
if (cachesExist) {
currentTimer = setTimeout(onTimer, options.interval);
}
};
server.ext({
type: 'onPostStart',
method: onTimer
});
server.events.on('stop', () => {
if (currentTimer) {
clearTimeout(currentTimer);
currentTimer = false;
}
});
};
exports.plugin = {
name: 'hapi-cache-stats',
register,
once: true,
pkg: require('./package.json')
};