class DashboardService {
// N+1 occurring
async getDashboardSlow() {
const users = await UserModel.getPuri("r").table("users").select("id", "name");
const stats = [];
for (const user of users) {
const orderCount = await OrderModel.getPuri("r")
.table("orders")
.select({ count: Puri.count() })
.where({ user_id: user.id });
const totalSpent = await OrderModel.getPuri("r")
.table("orders")
.select({ total: Puri.sum("total") })
.where({ user_id: user.id });
stats.push({
user: user.name,
orderCount: orderCount[0].count,
totalSpent: totalSpent[0].total,
});
}
return stats;
}
// Optimized with JOIN
async getDashboardFast() {
return UserModel.getPuri("r")
.table("users")
.select({
id: "users.id",
name: "users.name",
order_count: Puri.count("orders.id"),
total_spent: Puri.rawNumber("COALESCE(SUM(orders.total), 0)"),
})
.leftJoin("orders", "orders.user_id", "users.id")
.groupBy("users.id");
}
}