mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-08 12:32:43 +00:00
perf(illness): dedupe the active-episode read per request
resolveRestMode is resolved from several surfaces in one request — the snapshot builder, the recovery score, the analytics route, and coincident- deviation — each firing an identical active-episode findMany for the same account. Memoise the read per request keyed on (userId, asOf instant); an explicit client bypasses the memo so transaction and test reads are never served a default-client cached result.
This commit is contained in:
1 parent
04b0f38537
commit
075dae9ace
1 file changed
+19
@@ -26,6 +26,7 @@
|
||||
import type { PrismaClient, IllnessEpisode } from "@/generated/prisma/client";
|
||||
import { prisma as defaultPrisma } from "@/lib/db";
|
||||
import { isIllnessEnabled } from "@/lib/illness/gate";
|
||||
import { memoizePerRequest } from "@/lib/request-cache";
|
||||
|
||||
/** Minimal shape the Rest Mode resolver needs from an episode row. */
|
||||
export type ActiveIllnessEpisode = Pick<
|
||||
@@ -78,6 +79,24 @@ export async function getActiveIllnessEpisodes(
|
||||
userId: string,
|
||||
asOf: Date = new Date(),
|
||||
client: PrismaClient = defaultPrisma,
|
||||
): Promise<ActiveIllnessEpisode[]> {
|
||||
// Several surfaces resolve Rest Mode for the same `(userId, asOf)` inside
|
||||
// one request — the snapshot builder, the recovery score it builds, the
|
||||
// analytics route, and coincident-deviation — each firing an identical
|
||||
// `findMany`. Dedupe them to a single read per request. An explicit client
|
||||
// (a test stub or a transaction) bypasses the memo so its query is never
|
||||
// served a default-client cached result.
|
||||
if (client !== defaultPrisma) return readActiveIllnessEpisodes(userId, asOf, client);
|
||||
return memoizePerRequest(
|
||||
`illness-active-episodes:${userId}:${asOf.getTime()}`,
|
||||
() => readActiveIllnessEpisodes(userId, asOf, client),
|
||||
);
|
||||
}
|
||||
|
||||
async function readActiveIllnessEpisodes(
|
||||
userId: string,
|
||||
asOf: Date,
|
||||
client: PrismaClient,
|
||||
): Promise<ActiveIllnessEpisode[]> {
|
||||
if (!(await isIllnessEnabled(userId))) return [];
|
||||
return client.illnessEpisode.findMany({
|
||||
|
||||
Reference in new issue
Block a user