Cache the dashboard summary for a minute
Node · Node · beginner · modification
The dashboard summary runs three counting queries and the page polls it, so it is now a frequent, heavy query. This PR keeps each computed summary in an in-memory `Map` for 60 seconds in `src/routes/dashboard.ts`: a request with a fresh entry is answered from the map, otherwise the route queries as before, stores the result with its expiry time and answers. Only successful results are stored, so a failed query is retried on the next request.
Express 4 API in TypeScript (strict mode). It runs as a single Node process (one instance behind the load balancer), so an in-process `Map` is the whole cache. Existing, unchanged: `src/app.ts` mounts `app.use('/api/dashboard', requireAuth, dashboardRouter)` and ends with an error handler that logs and answers `500 { error: 'internal' }`; `requireAuth` answers `401` without a session and otherwise sets `req.user = { id }` (a positive integer), and the `Request` type is augmented so `req.user` is always set inside routes behind it. `getDashboardSummary(userId)` in `src/repos/dashboardRepo.ts` returns that user's three counts and rejects on a database error, and the module exports its `DashboardSummary` type; nothing mutates the object it returns. The app has at most 5,000 accounts, so one small summary per account fits in memory, and entries are replaced rather than deleted. Time comes from `Date.now()`, as everywhere in the app. Two simultaneous first requests may both run the query; that is accepted.
Requirements
- `GET /api/dashboard` keeps answering `200` with the signed-in user's own summary, `{ openTasks, overdueTasks, completedThisWeek }`, counted over that user's tasks, as before.
- To cut database load, a user's summary may be served from memory for up to 60 seconds after it was computed: a request inside that window gets the same numbers without a query, and the first request after it computes them again. Numbers about a minute old are fine.
- A user never sees another user's numbers.
- A failed summary query is not cached: the error goes to the app's error handler (`next(err)`) as before, and the user's next request tries the query again.
Files touched
- src/routes/dashboard.ts