This repository has been archived on 2026-05-02. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
GitBlog.md/src/hit_counter.js
T
2021-03-30 19:11:31 +02:00

49 lines
1.4 KiB
JavaScript

const redis = require('redis');
module.exports = (config, onConnect, onError) => {
const client = config['modules']['hit_counter'] ? redis.createClient(config['redis']) : { connected: false, on: () => { /* ignore */ } };
client.on('connect', onConnect);
client.on('error', onError);
const visitors = {};
const count = (req, path, cb) => {
if (!client.connected) {
cb();
} else {
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
const key = path + ':' + ip;
const now = Date.now();
const isNewVisitor = (now - (visitors[key] || 0)) > config['hit_counter']['unique_visitor_timeout'];
visitors[key] = now;
client
.multi()
.hincrby(path, 'h', 1)
.hincrby(path, 'v', isNewVisitor ? 1 : 0)
.exec(cb);
}
};
const read = (path, cb) => {
if (!client.connected) {
cb({
hits: 0,
visitors: 0,
});
} else {
client.hgetall(path, (_, value) => {
cb({
hits: value ? value.h || 0 : 0,
visitors: value ? value.v || 0 : 0,
});
});
}
};
return {
count: count,
read: read,
};
};