Files
HealthLog/src/lib/api/read-error.ts
T
Marc-André Bombeck c8ee4cb9fc feat(medications): shared helpers — readError + route-guards + dose-string + research-mode-types
Hoist five duplicated helpers into single source modules so each
contract evolves in exactly one place:

- src/lib/api/read-error.ts — replaces the four hand-rolled copies
  in the onboarding flow (Welcome / Goals / Source / Baseline).
- src/lib/medications/research-mode-types.ts — shared ResearchModeStatus
  DTO + tri-state gate helper consumed by both the DrugLevelChart
  and the Settings advanced section.
- src/lib/medications/route-guards.ts — assertMedicationOwnership
  for the eleven medication sub-routes, preserving the 404 leak
  shape across the privacy boundary.
- src/lib/medications/dose-string.ts — unified parseDoseMg + null
  variant replacing the DrugLevelChart and titration-route parsers.
- src/lib/medications/glp1-knowledge.ts — adds findDrugIdByBrand
  reverse lookup so the brand-to-id pattern stops being open-coded
  at every chart render.

28 new unit tests across the five helpers.
2026-05-14 22:54:25 +02:00

28 lines
1.0 KiB
TypeScript

/**
* v1.4.25 W21 Fix-N — shared client-side error reader.
*
* The four onboarding components (WelcomeCarousel, GoalsChipPicker,
* SourceCardGrid, BaselineForm) all hand-rolled the same helper to
* extract the `error` string from a non-OK `apiError` envelope, with an
* identical fall-through to `Request failed (<status>)`. Hoisting the
* helper keeps the four call sites honest — the envelope shape only
* needs to evolve once.
*
* Contract:
* - The server-side `apiError` helper writes `{ data: null, error: "<msg>" }`.
* - On parse failure (network error, non-JSON body, malformed shape)
* fall back to a stable string the toast can surface.
* - Never throw — the caller is already in a catch / setError path.
*/
export async function readError(res: Response): Promise<string> {
try {
const json = (await res.json()) as { error?: string };
if (typeof json.error === "string" && json.error.length > 0) {
return json.error;
}
} catch {
/* fall through */
}
return `Request failed (${res.status})`;
}