Skip to content

Commit 879bbfe

Browse files
committed
perf: implement caching for user listening statistics in historyController.
1 parent e6f54be commit 879bbfe

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

server/controllers/music/historyController.js.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const sequelize = require('../../utils/sequelize');
77
require('../../models/music/index');
88

99
const recommendationCache = new Map();
10+
const userStatsCache = new Map();
1011

1112
/* =========================
1213
HISTORY INSERT / UPDATE
@@ -374,6 +375,12 @@ const updateRecommendationScore = async (userId, songId) => {
374375
========================= */
375376

376377
const getUserListeningStats = async (userId) => {
378+
// Check cache first
379+
const cached = userStatsCache.get(userId);
380+
if (cached && cached.expiresAt > Date.now()) {
381+
return cached.data;
382+
}
383+
377384
const languages = await HistorySong.findAll({
378385
attributes: ['songLanguage', [sequelize.fn('COUNT', sequelize.col('songId')), 'count']],
379386
where: {
@@ -402,10 +409,18 @@ const getUserListeningStats = async (userId) => {
402409
raw: true,
403410
});
404411

405-
return {
412+
const stats = {
406413
preferredLanguages: languages.map((l) => l.songLanguage),
407414
preferredArtists: artists.flatMap((a) => a.artistNames.split(',').map((x) => x.trim())),
408415
};
416+
417+
// Cache for 15 minutes
418+
userStatsCache.set(userId, {
419+
expiresAt: Date.now() + 15 * 60 * 1000,
420+
data: stats,
421+
});
422+
423+
return stats;
409424
};
410425

411426
const calculateAlgorithmicScore = (song, stats) => {

0 commit comments

Comments
 (0)