SECTION 4: Debugging & Performance Optimization
// Wrap the entire logic in a try-catch block for error handling.
app.get("/orders", async (req, res) => {
try {
// Extract page and limit from the query parameters if not provided then set default values: page
= 1, limit = 10.
const { page = 1, limit = 10 } = req.query;
// Calculate the starting point for fetching data based on the page number and limit.
// number of rows to skip before starting to return data.
const offset = (page - 1) * limit;
// The main query to fetch orders.
// remove SELECT * it is fetching all columns and all rows — this increases the load time.
const orders = await db.query(
`SELECT id, customer_id, order_id
FROM orders
ORDER BY id DESC
LIMIT $1 OFFSET $2`,
[limit, offset] // it will Pass actual values for the placeholders ($1 = limit, $2 = offset).
);
res.send(orders);
} catch (error) {
// If something goes wrong, log the error for debugging.
console.error("Error:", error);
// Return a 503 server is temporarily unavailable.
res.status(503).send("Service Unavailable");
});
These point which is wrong
SELECT * is fetching all columns and all rows — this increases the load time.
No pagination — fetching too much data at once.
No indexing — the database is scanning the entire table instead of using optimized lookup
methods.
No sorting or filtering — the query is unstructured and unoptimized.