From b0ba52e1409d7a163b82aaa85ca726fa80c354d6 Mon Sep 17 00:00:00 2001 From: Klemek Date: Tue, 30 Mar 2021 15:30:54 +0200 Subject: [PATCH] work in progress hit_counter --- src/app.js | 20 ++++++++++++++++++-- src/hit_counter.js | 17 +++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 src/hit_counter.js diff --git a/src/app.js b/src/app.js index 0459650..55133c7 100644 --- a/src/app.js +++ b/src/app.js @@ -51,6 +51,7 @@ module.exports = (config) => { let showError; const fw = require('./file_walker')(config); const renderer = require('./renderer')(config); + const hc = require('./hit_counter')(config); // set view engine from configuration app.set('view engine', config['view_engine']); @@ -157,14 +158,22 @@ module.exports = (config) => { if (err) { showError(req, res, 404); } else { + hc.count(req, '/'); render(req, res, homePath, { articles: Object.values(articles) - .filter(d => !d.draft).sort((a, b) => ('' + b.path).localeCompare(a.path)) + .filter(d => !d.draft).sort((a, b) => ('' + b.path).localeCompare(a.path)), }); } }); }); + app.get('/stats', (req, res) => { + const data = hc.read('/'); + res.json({ + hits: data.hits, + visitors: data.visitors, + }); + }); //RSS endpoint app.get(config['rss']['endpoint'], (req, res) => { @@ -229,12 +238,19 @@ module.exports = (config) => { // catch all article urls and render them app.get('*', (req, res, next) => { - if (/^\/\d{4}\/\d{2}\/\d{2}\/$/.test(req.path)) { + if (/^\/\d{4}\/\d{2}\/\d{2}\/(stats)?$/.test(req.path)) { const articlePath = req.path.substr(1, 10); const article = articles[articlePath]; if (!article) { showError(req, res, 404); + } else if (req.path.endsWith('stats')) { + const data = hc.read(articlePath); + res.json({ + hits: data.hits, + visitors: data.visitors, + }); } else { + hc.count(req, articlePath); renderer.render(article.realPath, (err, html) => { if (err) { console.log(cons.error, `failed to render article ${req.path} : ${err}`); diff --git a/src/hit_counter.js b/src/hit_counter.js new file mode 100644 index 0000000..52c8141 --- /dev/null +++ b/src/hit_counter.js @@ -0,0 +1,17 @@ +module.exports = (config) => { + const count = (req, path) => { + + }; + + const read = (path) => { + return { + hits: 0, + visitors: 0, + }; + }; + + return { + count: count, + read: read, + }; +}; \ No newline at end of file