I am new to backend development and learning about nodejs and Mongodb i am developing a api for a company as an intern project but I am stuck in my problem
for almost 2 days can anyone please help me to fix this problem?
what I am trying to do is when I user hit the API from the client side the API takes user email from the body and finds that user with its email
and find its pet name like a dog,cat, etc the pet is a string after that if it finds a user with a similar pet name and if a user found with same pet name then
it will give that similar user in response till there everything was fine
but every user and only get one similar user with same pet name once a day so how can I also create an expirationTime of the next day and between that
time if a user tries to hit the API again it will give the same old user in response but to do all these things I need to keep track of the user
so I use Nodecache to store user email but here comes the problem that when I restart my server the cache is gone How can fix this problem? and store
cache data in Redis?
Normal Api:
router.post("/getuserwithpet", async (req, res) => {
try {
const { email } = req.body;
const user = await User.findOne({ email: email });
let pet = user.pet
const count = await User.countDocuments({ pet: pet });
if (count === 0) {
return res.status(404).json({ error: "No users found with that pet" });
}
const randomUser = await User.aggregate([
{ $match: { pet: pet, email: { $ne: email } }, },
{ $sample: { size: 1, }, },
{ $project: { name: 1, username: 1, profileImg: 1 } },
]);
res.json(randomUser);
} catch (err) {
console.log(err);
res.status(500).json({ error: err });
}
});
Node Cache api:
import NodeCache from 'node-cache';
const cache = new NodeCache();
router.post("/getuserwithpet", async (req, res) => {
try {
const { email } = req.body;
// Try to retrieve data from cache
const cachedData = cache.get(email);
if (cachedData) {
// If cached data is still valid, return it
const now = new Date();
if (cachedData.expiration > now) {
return res.json(cachedData.data);
}
}
// Retrieve user from database
const user = await User.findOne({ email: email });
let pet = user.pet;
const count = await User.countDocuments({ pet: pet });
if (count === 0) {
return res.status(404).json({ error: "No users found with that pet" });
}
let dataToCache;
if (cachedData && cachedData.data) {
dataToCache = cachedData.data;
} else {
dataToCache = await User.aggregate([
{ $match: { pet: pet, email: { $ne: email } }, },
{ $sample: { size: 1, }, },
{ $project: { name: 1, username: 1, profileImg: 1 } },
]);
}
const now = new Date();
const expiration = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, Math.floor(Math.random() * 6) + 5, 0, 0, 0);
const dataToCacheWithExpiration = { data: dataToCache, expiration: expiration };
cache.set(email, dataToCacheWithExpiration);
res.json(dataToCache);
} catch (err) {
console.log(err);
res.status(500).json({ error: err });
}
});