made changes in get tank data

master
Varun 10 months ago
parent 58368736c8
commit 858451563b

@ -208,68 +208,37 @@ exports.getConnectionsInfoOfParticularTank = async (req, reply) => {
//get tanks data by passing username //get tanks data by passing username
exports.getTank = async (req, reply) => { exports.getTank = async (req, reply) => {
try { try {
const { customerId } = req.params; await Tank.find({ customerId: req.query.customerId })
.exec()
// Aggregate to count need_sensor values .then((docs) => {
const needSensorCounts = await Tank.aggregate([ // Transform the response to include switch_count
{ $match: { customerId } }, const transformedDocs = docs.map((tank) => {
{ const inputConnections = tank.connections?.inputConnections || [];
$group: { const switchCount = inputConnections.reduce((count, connection) => {
_id: "$need_sensor", return count + (connection.inputismotor === true ? 1 : 0);
count: { $sum: 1 }, }, 0);
},
},
]);
const inputIsMotorCounts = await Tank.aggregate([ // Add the switch_count field inside connections
{ $match: { customerId } }, return {
{ $unwind: "$connections.inputConnections" }, ...tank.toObject(), // Convert Mongoose document to plain object
{ connections: {
$group: { ...tank.connections,
_id: "$connections.inputConnections.inputismotor", switch_count: switchCount,
count: { $sum: 1 },
},
}, },
]); };
});
// Retrieve all tank documents for the customerId
const tanks = await Tank.find({ customerId }).exec();
// Format the aggregation results
const needSensorResult = needSensorCounts.reduce((acc, item) => {
if (item._id === "yes") {
acc["yes"] = item.count;
}
return acc;
}, {});
const inputIsMotorResult = inputIsMotorCounts.reduce((acc, item) => {
if (item._id === true) {
acc["true"] = item.count;
}
return acc;
}, {});
// Return the combined response reply.send({ status_code: 200, data: transformedDocs, count: transformedDocs.length });
reply.send({ })
status_code: 200, .catch((err) => {
customerId, console.error(err);
needSensor: { reply.send({ status_code: 500, error: err.message });
yes: needSensorResult["YES"] || 0,
},
inputIsMotor: {
true: inputIsMotorResult["true"] || 0,
},
tanks: {
data: tanks,
count: tanks.length,
},
}); });
} catch (error) { } catch (err) {
reply.status(500).send({ error: "An error occurred while fetching the data." }); console.error(err);
reply.send({ status_code: 500, error: "Internal Server Error" });
} }
}, };
@ -316,7 +285,6 @@ exports.getTanksensorcount = async (req, reply) => {
}); });
reply.send({ reply.send({
alltanks:tanks,
customerId, customerId,
tanks: tankResults, tanks: tankResults,
}); });

Loading…
Cancel
Save