I've been tackling this code and wondering if there's a sleeker way to handle it. As it stands, the code is starting to become unruly, resembling a tangled mess. This specific code snippet involves MariahDB + Express.
app.get
("/ordersInfo", function (req, res) {
connection.query("SELECT SUM(`subtotal`) as data FROM `orders` WHERE created_at BETWEEN '" + moment().startOf("day").format() + "' AND '" + moment().endOf("day").format() + "'", (err, dailyTotalRevenue) => {
connection.query("SELECT SUM(`subtotal`) as data FROM `orders` WHERE created_at BETWEEN '" + moment().startOf("week").format() + "' AND '" + moment().endOf("week").format() + "'", (err, weeklyTotalRevenue) => {
connection.query("SELECT SUM(`subtotal`) as data FROM `orders` WHERE created_at BETWEEN '" + moment().startOf("month").format() + "' AND '" + moment().endOf("month").format() + "'", (err, monthlyTotalRevenue) => {
connection.query("SELECT COUNT(*) as data FROM `orders` WHERE created_at BETWEEN '" + moment().startOf("day").format() + "' AND '" + moment().endOf("day").format() + "'", (err, dailyTotalOrderCount) => {
connection.query("SELECT COUNT(*) as data FROM `orders` WHERE created_at BETWEEN '" + moment().startOf("week").format() + "' AND '" + moment().endOf("week").format() + "'", (err, weeklyTotalOrderCount) => {
connection.query("SELECT COUNT(*) as data FROM `orders` WHERE created_at BETWEEN '" + moment().startOf("month").format() + "' AND '" + moment().endOf("month").format() + "'", (err, monthlyTotalOrderCount) => {
connection.query("SELECT * FROM `orders` WHERE created_at BETWEEN '" + moment().startOf("month").format() + "' AND '" + moment().endOf("month").format() + "'", (err, month) => {
connection.query("SELECT COUNT(*) as data FROM `orders` WHERE status = 'pending'", (err, totalPending) => {
connection.query("SELECT COUNT(*) as data FROM `orders` WHERE status = 'ready_to_ship'", (err, totalReadyToShip) => {
if (err) {
console.log(err);
res.json({ error: true });
} else {
return res.json({
daily: {
totalRevenue: (dailyTotalRevenue[0].data) ? dailyTotalRevenue[0].data : 0,
totalOrderCount: (dailyTotalOrderCount[0].data) ? dailyTotalOrderCount[0].data : 0,
},
weekly: {
totalRevenue: (weeklyTotalRevenue[0].data) ? weeklyTotalRevenue[0].data : 0,
totalOrderCount: (weeklyTotalOrderCount[0].data) ? weeklyTotalOrderCount[0].data : 0,
},
monthly: {
totalRevenue: (monthlyTotalRevenue[0].data) ? monthlyTotalRevenue[0].data : 0,
totalOrderCount: (monthlyTotalOrderCount[0].data) ? monthlyTotalOrderCount[0].data : 0,
},
total: {
totalPending: totalPending[0].data,
totalReadyToShip: totalReadyToShip[0].data,
}
});
}
});
});
});
});
});
});
});
});
});
});
The outcome appears as shown in this image:
https://i.sstatic.net/I3M7f.png
While the current setup gets the job done, I'm anticipating needing additional information from that same database table. Is there a more streamlined and effective way to tackle this?