mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 23:12:04 +00:00
fix(api): one helper for list pages, exact cut signal, total order
listPage (src/lib/http/list-query.ts) reads one row past the limit and cuts it back, on top of the existing list-cap signal rather than beside it. Every capped list now gets its page there, and every read passed to it orders by something ending in the row id, so rows that share a sort value cannot repeat or vanish at a page boundary. - practitioners, vaccinations and encounters were cut at their take with no signal; they now answer meta.truncated and accept offset, and their web readers walk the pages instead of stopping at the first - symptoms/events reported hasMore on a page that was exactly full; it is now true only when a row past the page exists - the document list's hand-rolled limit + 1 goes through the helper - security-activity answers an out-of-range limit with the 422 its published schema already promised instead of clamping it list-page-guard binds every apiListSuccess route to listPage, forbids hand-cut lists and length-derived hasMore, and requires the id tiebreaker in every listPage read.
This commit is contained in:
1 parent
2265763160
commit
8db7c71b0e
35 files changed
+1024
-394
No files matched your search
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { combinedCap, listPage, parseListQuery } from "../list-query";
|
||||
|
||||
describe("listPage", () => {
|
||||
it("asks for one row past the limit and reports a cut only when that row exists", async () => {
|
||||
const read = vi.fn(async (take: number) =>
|
||||
Array.from({ length: Math.min(take, 5) }, (_, i) => i),
|
||||
);
|
||||
|
||||
const cut = await listPage(3, read);
|
||||
expect(read).toHaveBeenLastCalledWith(4);
|
||||
expect(cut.rows).toEqual([0, 1, 2]);
|
||||
expect(cut.cap).toEqual({ truncated: true, limit: 3 });
|
||||
|
||||
// Exactly full is complete: five rows, a limit of five.
|
||||
const full = await listPage(5, read);
|
||||
expect(full.rows).toHaveLength(5);
|
||||
expect(full.cap).toEqual({ truncated: false, limit: 5 });
|
||||
|
||||
const short = await listPage(9, read);
|
||||
expect(short.rows).toHaveLength(5);
|
||||
expect(short.cap.truncated).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("combinedCap", () => {
|
||||
it("is truncated when any list was cut", () => {
|
||||
expect(
|
||||
combinedCap(
|
||||
{ truncated: false, limit: 50 },
|
||||
{ truncated: true, limit: 50 },
|
||||
),
|
||||
).toEqual({ truncated: true, limit: 50 });
|
||||
expect(
|
||||
combinedCap(
|
||||
{ truncated: false, limit: 50 },
|
||||
{ truncated: false, limit: 50 },
|
||||
).truncated,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseListQuery", () => {
|
||||
const options = { defaultLimit: 50, maxLimit: 200, offset: true };
|
||||
|
||||
it("applies the default and reads both fields", () => {
|
||||
expect(parseListQuery(new URLSearchParams(), options).data).toEqual({
|
||||
limit: 50,
|
||||
offset: 0,
|
||||
});
|
||||
expect(
|
||||
parseListQuery(new URLSearchParams("limit=10&offset=20"), options).data,
|
||||
).toEqual({ limit: 10, offset: 20 });
|
||||
});
|
||||
|
||||
it("refuses a limit past the ceiling and a negative offset, both at once", () => {
|
||||
const parsed = parseListQuery(
|
||||
new URLSearchParams("limit=500&offset=-1"),
|
||||
options,
|
||||
);
|
||||
expect(parsed.success).toBe(false);
|
||||
expect(parsed.error?.issues.map((i) => i.path[0]).sort()).toEqual([
|
||||
"limit",
|
||||
"offset",
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignores offset on a route that does not page", () => {
|
||||
expect(
|
||||
parseListQuery(new URLSearchParams("offset=20"), {
|
||||
defaultLimit: 50,
|
||||
maxLimit: 200,
|
||||
}).data,
|
||||
).toEqual({ limit: 50, offset: 0 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* The `limit` and `offset` query fields of a paged list, safe for any bundle.
|
||||
*
|
||||
* Kept apart from `./list-query.ts` (which reaches the response envelope) so a
|
||||
* request schema in `src/lib/validations/` can use them without pulling server
|
||||
* code into a client that imports the same schema.
|
||||
*/
|
||||
import { z } from "zod";
|
||||
|
||||
/** The `limit` field, for a route whose query schema has other fields too. */
|
||||
export function listLimitField({
|
||||
defaultLimit,
|
||||
maxLimit,
|
||||
}: {
|
||||
defaultLimit: number;
|
||||
maxLimit: number;
|
||||
}) {
|
||||
return z.coerce.number().int().min(1).max(maxLimit).default(defaultLimit);
|
||||
}
|
||||
|
||||
/** The `offset` field, for a route whose query schema has other fields too. */
|
||||
export function listOffsetField() {
|
||||
return z.coerce.number().int().min(0).max(100_000).default(0);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* One way to read a page of a list, and one way to say whether it was cut.
|
||||
*
|
||||
* The list routes had grown five answers to "is there more": `meta.truncated`
|
||||
* from `src/lib/api/list-cap.ts`, a `hasMore` computed as `rows.length ===
|
||||
* limit` (true on a list that is exactly full, so a client asks for a page
|
||||
* that does not exist), a `total` from a second count query, a sync cursor,
|
||||
* and nothing at all. This module is where a capped or paged list gets its
|
||||
* page, so the signal is computed the same way everywhere:
|
||||
*
|
||||
* - {@link parseListQuery} reads `limit` (and `offset`, where the route
|
||||
* pages) with the route's own default and ceiling;
|
||||
* - {@link listPage} runs the read for one row past the limit and cuts it
|
||||
* back, so `cap.truncated` is exact: true only when a row past the page
|
||||
* exists.
|
||||
*
|
||||
* The cap is the one in `list-cap.ts` — this module adds no second signal.
|
||||
* A route answers with `apiListSuccess(data, cap)` (the envelope's `meta`),
|
||||
* or, where a route already published a `hasMore` in its body, derives that
|
||||
* field from `cap.truncated`.
|
||||
*
|
||||
* Every read through here must have a total order: the `orderBy` ends in the
|
||||
* row id, so a page boundary between two rows that share a timestamp does not
|
||||
* repeat one of them on the next page or drop it. `list-page-guard.test.ts`
|
||||
* holds every capped list to this module and to that tiebreaker.
|
||||
*/
|
||||
import { z } from "zod";
|
||||
|
||||
import { capRows, overfetch, type ListCap } from "@/lib/api/list-cap";
|
||||
|
||||
import { listLimitField, listOffsetField } from "./list-query-fields";
|
||||
|
||||
export { listLimitField, listOffsetField } from "./list-query-fields";
|
||||
|
||||
export interface ListQueryOptions {
|
||||
/** The limit when the request names none. */
|
||||
defaultLimit: number;
|
||||
/** The largest limit a request may ask for. */
|
||||
maxLimit: number;
|
||||
/** Whether the route pages with `offset`. */
|
||||
offset?: boolean;
|
||||
}
|
||||
|
||||
export interface ListQuery {
|
||||
limit: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read `limit` (and `offset`) from a request's query string.
|
||||
*
|
||||
* Returns the Zod result, so the route answers a bad value with the same
|
||||
* multi-issue 422 it gives every other field.
|
||||
*/
|
||||
export function parseListQuery(
|
||||
params: URLSearchParams,
|
||||
options: ListQueryOptions,
|
||||
) {
|
||||
const schema = z.object({
|
||||
limit: listLimitField(options),
|
||||
offset: options.offset ? listOffsetField() : z.literal(0).default(0),
|
||||
});
|
||||
return schema.safeParse({
|
||||
limit: params.get("limit") ?? undefined,
|
||||
offset: options.offset ? (params.get("offset") ?? undefined) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a list read for one page and say whether rows past it exist.
|
||||
*
|
||||
* `read` receives the `take` to pass to Prisma (one past `limit`); the rows
|
||||
* come back cut to `limit` with the exact cap beside them.
|
||||
*/
|
||||
export async function listPage<T>(
|
||||
limit: number,
|
||||
read: (take: number) => Promise<readonly T[]>,
|
||||
): Promise<{ rows: T[]; cap: ListCap }> {
|
||||
return capRows(await read(overfetch(limit)), limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* The cap of a response that carries several capped lists at once (the
|
||||
* encounters' upcoming and past arms, the grants given and received): more
|
||||
* rows exist when any one of them was cut.
|
||||
*/
|
||||
export function combinedCap(...caps: ListCap[]): ListCap {
|
||||
return {
|
||||
truncated: caps.some((cap) => cap.truncated),
|
||||
limit: Math.max(...caps.map((cap) => cap.limit)),
|
||||
};
|
||||
}
|
||||
@@ -392,6 +392,7 @@ export const ERROR_CODE_CATALOGUE: Readonly<Record<string, readonly string[]>> =
|
||||
],
|
||||
route: ["route.retired"],
|
||||
search: ["search.invalid"],
|
||||
security_activity: ["security_activity.invalid"],
|
||||
"share-link": [
|
||||
"share-link.document.decryptFailed",
|
||||
"share-link.document.notFound",
|
||||
|
||||
@@ -1708,7 +1708,7 @@ export const authPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Auth"],
|
||||
summary: "List recent account-security activity",
|
||||
description:
|
||||
"v1.23 — the SHARED security-activity feed: the caller's recent auth + export + deletion audit events with timestamp, resolved location, and a host-masked IP. `limit` query param caps at 100 (default 50). Reuses the AuditLog store; no event detail bodies are surfaced.",
|
||||
"v1.23 — the SHARED security-activity feed: the caller's recent auth + export + deletion audit events with timestamp, resolved location, and a host-masked IP. `limit` is 1-100 (default 50); a value outside that is a 422 naming it. Reuses the AuditLog store; no event detail bodies are surfaced.",
|
||||
requestParams: {
|
||||
query: z.object({
|
||||
limit: z.coerce
|
||||
@@ -1717,7 +1717,9 @@ export const authPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
.min(1)
|
||||
.max(100)
|
||||
.optional()
|
||||
.describe("Page size; defaults to 50, clamped to 100."),
|
||||
.describe(
|
||||
"Page size, 1-100; defaults to 50. Out of range is a 422.",
|
||||
),
|
||||
}),
|
||||
},
|
||||
responses: {
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
errorEnvelope,
|
||||
idempotencyKeyParameter,
|
||||
idempotentWrite,
|
||||
listEnvelope,
|
||||
recordRefusal,
|
||||
recordWriteRateLimitResponse,
|
||||
stdResponses,
|
||||
@@ -346,7 +347,7 @@ export const encounterPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Records"],
|
||||
summary: "List visits",
|
||||
description:
|
||||
"Returns the caller's live visits, split into `upcoming` and `past`. Bounded and windowed; soft-deleted visits are excluded.",
|
||||
"Returns the caller's live visits, split into `upcoming` (soonest first) and `past` (newest first). `limit` and `offset` apply to each list; `meta.truncated` is true when either list has rows past this page, so a client reads the next `offset` until it is false. Soft-deleted visits are excluded.",
|
||||
requestParams: { query: listEncountersQuery },
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
@@ -354,7 +355,7 @@ export const encounterPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
description: "The caller's visits.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(encounterList, "ListEncountersEnvelope"),
|
||||
schema: listEnvelope(encounterList, "ListEncountersEnvelope"),
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -612,7 +613,7 @@ export const encounterPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Records"],
|
||||
summary: "List practitioners",
|
||||
description:
|
||||
"Returns the caller's address book, name-ordered, with an optional case-insensitive name search.",
|
||||
"Returns the caller's address book, name-ordered, with an optional case-insensitive search over name, practice and specialty. Paged with `limit` and `offset`; `meta.truncated` says whether another page exists.",
|
||||
requestParams: { query: listPractitionersQuery },
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
@@ -620,7 +621,7 @@ export const encounterPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
description: "The caller's address book.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
schema: listEnvelope(
|
||||
z.array(practitioner),
|
||||
"ListPractitionersEnvelope",
|
||||
),
|
||||
|
||||
@@ -119,7 +119,7 @@ const symptomEventList = z
|
||||
.meta({
|
||||
id: "SymptomEventList",
|
||||
description:
|
||||
"A page of occurrences, newest first. `hasMore` is true when the page is full; page on with `to` set to the oldest `occurredAt` seen.",
|
||||
"A page of occurrences, newest first. `hasMore` is true exactly when an occurrence past this page exists; page on with `to` set to the oldest `occurredAt` seen.",
|
||||
});
|
||||
|
||||
const deletedResponse = z
|
||||
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
recordRefusal,
|
||||
recordWriteRateLimitResponse,
|
||||
stdResponses,
|
||||
listEnvelope,
|
||||
} from "./shared";
|
||||
import { isoDateTime } from "@/lib/validations/datetime";
|
||||
|
||||
@@ -413,7 +414,7 @@ export const vaccinationPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Records"],
|
||||
summary: "List vaccinations",
|
||||
description:
|
||||
"Returns the caller's live doses, newest first, each with its series resolved per component antigen. Soft-deleted doses are excluded.",
|
||||
"Returns the caller's live doses, newest first, each with its series resolved per component antigen over the whole record, never over the page. Paged with `limit` (default 300) and `offset`; `meta.truncated` says whether another page exists. Soft-deleted doses are excluded.",
|
||||
requestParams: { query: listVaccinationsQuery },
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
@@ -421,7 +422,7 @@ export const vaccinationPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
description: "The caller's immunization history.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(vaccinationList, "ListVaccinationsEnvelope"),
|
||||
schema: listEnvelope(vaccinationList, "ListVaccinationsEnvelope"),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { listOffsetField } from "@/lib/http/list-query-fields";
|
||||
|
||||
export const practitionerCreateSchema = z
|
||||
.object({
|
||||
name: z.string().min(1).max(160),
|
||||
@@ -50,6 +52,11 @@ export const practitionerListQuerySchema = z
|
||||
.object({
|
||||
q: z.string().min(1).max(160).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(200).optional(),
|
||||
offset: listOffsetField()
|
||||
.optional()
|
||||
.describe(
|
||||
"Rows to skip, for reading the address book page by page; `meta.truncated` says whether another page exists.",
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
* moment the catalogue is authoritative, because the picker produced it.
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
import { listOffsetField } from "@/lib/http/list-query-fields";
|
||||
|
||||
import {
|
||||
ANTIGEN_SLUGS,
|
||||
@@ -195,6 +196,11 @@ export const vaccinationListQuerySchema = z
|
||||
from: isoDateTime().optional(),
|
||||
to: isoDateTime().optional(),
|
||||
limit: z.coerce.number().int().min(1).max(500).optional(),
|
||||
offset: listOffsetField()
|
||||
.optional()
|
||||
.describe(
|
||||
"Doses to skip, for reading the log page by page; `meta.truncated` says whether another page exists.",
|
||||
),
|
||||
})
|
||||
.strict()
|
||||
.refine((q) => !(q.from && q.to) || q.from <= q.to, {
|
||||
|
||||
Reference in new issue
Block a user