I am facing a problem to update the values stored in map to database because the map is updating continously due to incoming requests on the route and at the same time I want to update values in database periodically with the help of map. How to synchronize both the operations?
const url_count = new Map();
async function update_count(){
// update value in mongodb
}
app.get('/teeny/:code', async (req, res) => {
try {
const url = await Link_URL.findOne({
_id : req.params.code
})
if (url) {
if(url_count.has(req.params.code)){
const val = url_count.get(req.params.code);
url_count.set(req.params.code,val+1);
update_count();
}
else{
url_count.set(req.params.code,1);
}
return res.redirect(url.URL);
} else {
return res.status(404).json('No URL Found')
}
}
catch (err) {
console.error(err)
res.status(500).json('Server Error')
}
})
cron.schedule('* * 1 * *', update_count);
You could use Later for a simple solution... here you would be collecting all those values and then insert them at a specified time that you specified in later..
For something heavier, you could go for Bull or for Rabbot
If you want to kill a lion, go for Node-Celery... but make sure to have python installed.
Basically, all you need is a queuing system to collect[in a queue] all those tasks that you want to save later...