Before you make the shop faster, measure it: otherwise you can't tell whether a change really helped. In this module you measure the work a request does by counting its database queries. A count gives the same answer on every computer, while a time in milliseconds changes with the machine and with whatever else it is doing.
Every route in the shop asks the database through one helper, RunQuery, so that is the one place to count: a wrapper that does its job and keeps score on the way. The score lives in a dictionary made at the top of the file, so RunQuery and every route can reach it. Here is the same idea on another value, a counter of visits:
var visits = new Dictionary<string, int> { ["count"] = 0 };
app.MapGet("/hello", () => {
visits["count"] += 1;
return Results.Json(new { message = "Hi!", count = visits["count"] });
});
To read the count, add a debug route: a tool for you, the developer, not a page for customers. The count only goes up, so read it before and after a request: the difference is what that request cost. Your code must give these answers, in this order:
GET /debug/queries → 200 {"queries": 0}
GET /products/1 → 200 {"category": "kitchen", "id": 1, "name": "Mug", "price": 12, "stock": 10}
GET /debug/queries → 200 {"queries": 1}
GET /customers/1/orders → 200 [{"id": 1, "items": […], …}, {"id": 3, "items": […], …}]
GET /debug/queries → 200 {"queries": 4}
GET /customers/5/orders → 200 []
GET /debug/queries → 200 {"queries": 5}
Customer 1's orders cost 3 queries: one for the orders, then one for the items of each of the 2 orders. Customer 5 has no orders, so only the first query runs. Reading the count is not a query, so it never counts itself.
Your task: below db.Open();, add a dictionary stats whose key "queries" starts at 0, make RunQuery add 1 to it every time it runs, and add a route for GET /debug/queries that answers stats with Results.Json.
Assignment
Follow the Coding Tutorial to count every query in RunQuery and show the count at GET /debug/queries.
Hint
The counting line goes first in RunQuery, the helper every route uses. += 1 adds one to the value already in the dictionary.
Free plan: 30 tutor messages. PRO is unlimited.
