Log number of requests to endpoints in DB

This commit is contained in:
Christopher Cookman 2024-12-23 17:11:22 -07:00
parent 9520086bfe
commit 459d610c60
4 changed files with 26 additions and 1 deletions

16
analytics.js Normal file
View file

@ -0,0 +1,16 @@
const pool = global.db_pool
module.exports = (req, res, next) => {
next();
const { path, method } = req;
pool.query(
'INSERT INTO analytics (method, endpoint, count) VALUES (?, ?, 1) ON DUPLICATE KEY UPDATE count = count + 1',
[method, path],
(error, results) => {
if (error) {
console.error('Error logging analytics:', error);
}
}
);
}

View file

@ -77,6 +77,9 @@ app.use((req, res, next) => {
next() next()
}); });
const analytics = require('./analytics.js');
app.use(analytics);
// Rate Limit middleware from scratch // Rate Limit middleware from scratch
const rateLimit = require('./rateLimit.js'); const rateLimit = require('./rateLimit.js');

View file

@ -0,0 +1,7 @@
CREATE TABLE analytics (
id INT AUTO_INCREMENT PRIMARY KEY,
method VARCHAR(255) NOT NULL,
endpoint VARCHAR(255) NOT NULL,
UNIQUE (method, endpoint),
count INT NOT NULL DEFAULT 0
);

View file

@ -22,7 +22,6 @@ router.use(express.json());
router.use(express.urlencoded({ extended: true })); router.use(express.urlencoded({ extended: true }));
router.use(expressSession({ router.use(expressSession({
store: expressSession.MemoryStore(), store: expressSession.MemoryStore(),
secret: process.env.SESSION_SECRET || 'default_secret', secret: process.env.SESSION_SECRET || 'default_secret',