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

Loading…
Cancel
Save