Skip to content

Commit

Permalink
✨ feat: 조회수 캐싱 기능 추가 Murakano#99
Browse files Browse the repository at this point in the history
  • Loading branch information
jjikky committed Oct 29, 2024
1 parent 6e323fb commit d628e76
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
13 changes: 10 additions & 3 deletions src/routes/word/word.model.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const mongoose = require('mongoose');
const redisClient = require('../../common/modules/redis');

const wordSchema = new mongoose.Schema(
{
Expand All @@ -14,9 +15,15 @@ const wordSchema = new mongoose.Schema(

wordSchema.index({ word: 1 });

wordSchema.pre(/^findOne/, async function (next) {
await this.model.updateOne(this.getQuery(), { $inc: { freq: 1 } });
next();
wordSchema.post(/^findOne/, async function (doc) {
const word = typeof this.getQuery().word === 'string' ? this.getQuery().word : doc?.word;
if (!word) {
console.error('❌ Error: No valid word found for Redis update');
return;
}

await redisClient.sendCommand(['ZINCRBY', 'popular_words', '1', word]);
await redisClient.expire('popular_words', 7200);
});

wordSchema.pre(/^find|update|save|remove|delete|count/, function (next) {
Expand Down
20 changes: 18 additions & 2 deletions src/routes/word/word.repository.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
const Word = require('./word.model');
const redisClient = require('../../common/modules/redis');

exports.getSearchWords = async (searchTerm) => {
return await Word.findOne({ word: { $regex: `^${searchTerm}$`, $options: 'i' } });
};

exports.getRankWords = async () => {
const words = await Word.find().sort({ freq: -1 }).limit(10);
return words.map((word) => word.word);
const words = await redisClient.sendCommand(['ZREVRANGE', 'popular_words', '0', '9']);

if (words && words.length > 0) {
return words;
}

const dbWords = await Word.find().sort({ freq: -1 }).limit(10).select('word freq').lean();
const wordList = dbWords.map((word) => word.word);

await redisClient.sendCommand([
'ZADD',
'popular_words',
...dbWords.flatMap((word) => [String(word.freq), word.word]),
]);
await redisClient.expire('popular_words', 7200);

return wordList;
};

exports.getRelatedWords = async (searchTerm, limit) => {
Expand Down

0 comments on commit d628e76

Please sign in to comment.