From 8702c293c783a1a3a10b16d3561daefb1ad90299 Mon Sep 17 00:00:00 2001 From: varun Date: Tue, 28 Feb 2023 04:30:56 -0500 Subject: [PATCH] made changes in tanks controller --- src/controllers/tanksController.js | 74 +++++++++++++++--------------- 1 file changed, 36 insertions(+), 38 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 8d3a79fc..748191ff 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -142,54 +142,52 @@ exports.getTank = async (req, reply) => { //}; - exports.updateTanklevels = async (req, reply) => { - try { - const customerId = req.params.customerId; - const tank = await Tank.find({customerId}); + const customerId = req.params.customerId; + const tanks = await Tank.find({ customerId }); - - for (var i=0; i < tank.length; i++) { - const tankname = tank[i].tankName - const capacity = (tank[i].capacity).replace(/,/g, "") - - let Number = capacity-100 //Math.floor(Math.random() * capacity) - - - - //console.log(Number) - setInterval(async function () { - - // const randomNumber = Math.floor(Math.random() * capacity) - //const randomNumber = Math.floor(Math.random() * (5500 - 1000) + 1000); - - //console.log(tankname) - const randomNumber = Math.floor(Number/1.5) - - - const tank_info =await Tank.findOneAndUpdate({customerId:customerId,tankName:tankname},{$set:{waterlevel:randomNumber}}) - console.log(tank_info) - Number = randomNumber - - //return Number - - }, 2000); - } - - - - - return { message: 'Water level will be updated every 2 seconds' }; - } + const intervals = {}; + + for (const tank of tanks) { + const tankName = tank.tankName; + let capacity = parseInt(tank.capacity.replace(/,/g, ''), 10); + + let waterLevel = capacity - 100; // initial water level + const intervalId = setInterval(async function () { + const newWaterLevel = Math.floor(waterLevel / 1.5); + + const result = await Tank.findOneAndUpdate( + { customerId, tankName }, + { $set: { waterlevel: newWaterLevel } } + ); + + console.log(result); + + if (newWaterLevel === 0) { + clearInterval(intervals[tankName]); + console.log(`Stopped updating ${tankName}`); + return; + } - catch (err) { + waterLevel = newWaterLevel; + }, 2000); + + intervals[tankName] = intervalId; + } + + return { message: 'Water level updates started' }; + } catch (err) { throw boom.boomify(err); } }; + + + + exports.getTanklevels = async (req, reply) => { try { const customerId = req.params.customerId;