mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 08:02:12 +00:00
feat(api): aggregator endpoints for headless API clients
Adds seven read/write endpoints that aggregate or adapt existing data
into shapes more practical for non-browser consumers. None of the
pre-existing endpoints are touched.
• `GET /api/dashboard/summary` — greeting + streak + today compliance
+ per-metric latest value with 7-day sparkline. Single round-trip
for a "home" view instead of fanning out across 6 endpoints.
• `GET /api/measurements/series?kind=&days=` — pre-aggregated series +
stats (mean, min, max, stdDev, count) reusing
`src/lib/analytics/trends.ts`.
• `GET/PATCH /api/integrations/healthkit` — opt-in per-metric sync
config (entries[] of `{ id, kind, direction, enabled }`). Stored in
the new `users.healthkit_config_json` column.
• `POST /api/devices` — APNs/FCM token registration only; no push
sender wired up here. Upsert on `token`.
• `GET /api/medications/intake?scope=today|compliance` — top-level
aggregator over all of a user's medications, plus a sibling
`POST /api/medications/intake` accepting `{ intakeId, status, takenAt }`
for clients that don't want to maintain medication-id state.
• `GET /api/insights/cards` — adapter that maps the rule-based alerts
from `/api/insights/comprehensive` into card-shaped `Insight[]`.
• `GET /api/insights/correlations` — placeholder array today; flagged
in audit log as `insights.correlations.empty` until a real engine
lands.
All endpoints honour `requireAuth()` (cookie or bearer) and the existing
audit/Wide-Event pipeline.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
98e209b6f7
commit
1f5ad1729d
14 files changed
+1939
No files matched your search
@@ -0,0 +1,112 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: { findUnique: vi.fn(), update: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: () => null })),
|
||||
cookies: vi.fn(async () => ({ get: () => undefined, set: () => {}, delete: () => {} })),
|
||||
}));
|
||||
|
||||
import { GET, PATCH } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
user: { id: "user-1", username: "marc", role: "USER" as const },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
healthKitConfigJson: null,
|
||||
healthKitLastSyncedAt: null,
|
||||
} as never);
|
||||
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
|
||||
});
|
||||
|
||||
const callGet = GET as unknown as (req: NextRequest) => Promise<Response>;
|
||||
function makeGetReq(): NextRequest {
|
||||
return new NextRequest("http://localhost/api/integrations/healthkit");
|
||||
}
|
||||
|
||||
describe("GET /api/integrations/healthkit", () => {
|
||||
it("returns 401 when unauthenticated", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(null);
|
||||
const res = await callGet(makeGetReq());
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns the default entries when nothing is stored", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
const res = await callGet(makeGetReq());
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as {
|
||||
data: { entries: Array<{ id: string; direction: string }> };
|
||||
};
|
||||
expect(body.data.entries.length).toBeGreaterThan(0);
|
||||
const bodyMass = body.data.entries.find((e) => e.id === "bodyMass");
|
||||
expect(bodyMass?.direction).toBe("bidirectional");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PATCH /api/integrations/healthkit", () => {
|
||||
function req(body: unknown): NextRequest {
|
||||
return new NextRequest("http://localhost/api/integrations/healthkit", {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
it("returns 401 when unauthenticated", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(null);
|
||||
const res = await PATCH(req({ entries: [] }));
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns 422 for invalid direction", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
const res = await PATCH(
|
||||
req({ entries: [{ id: "bodyMass", direction: "FOO" }] }),
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
});
|
||||
|
||||
it("updates known entries and silently ignores unknown ids", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
const res = await PATCH(
|
||||
req({
|
||||
entries: [
|
||||
{ id: "bodyMass", direction: "readOnly" },
|
||||
{ id: "totallyUnknown", direction: "bidirectional" },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.user.update).toHaveBeenCalledTimes(1);
|
||||
const updateArgs = vi.mocked(prisma.user.update).mock.calls[0][0] as unknown as {
|
||||
data: { healthKitConfigJson: { entries: Array<{ id: string }> } };
|
||||
};
|
||||
const ids = updateArgs.data.healthKitConfigJson.entries.map((e) => e.id);
|
||||
expect(ids).toContain("bodyMass");
|
||||
expect(ids).not.toContain("totallyUnknown");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* HealthKit (iOS) integration config.
|
||||
*
|
||||
* Persisted on `User.healthKitConfigJson` as `{ entries: [...] }`.
|
||||
* Each entry: `{ id, kind, direction, enabled }` where `direction` is one
|
||||
* of `bidirectional | readOnly | writeOnly`.
|
||||
*
|
||||
* GET → resolved config (with default entries when nothing is stored).
|
||||
* PATCH → merge by `id`; unknown ids are silently ignored.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiError, apiSuccess, safeJson } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { Prisma } from "@/generated/prisma/client";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
|
||||
export const directionEnum = z.enum([
|
||||
"bidirectional",
|
||||
"readOnly",
|
||||
"writeOnly",
|
||||
"disabled",
|
||||
]);
|
||||
|
||||
const entrySchema = z.object({
|
||||
id: z.string().min(1).max(64),
|
||||
kind: z.string().min(1).max(64).optional(),
|
||||
direction: directionEnum,
|
||||
enabled: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const patchSchema = z.object({
|
||||
entries: z.array(entrySchema).max(50),
|
||||
});
|
||||
|
||||
export interface HealthKitEntry {
|
||||
id: string;
|
||||
kind: string;
|
||||
direction: z.infer<typeof directionEnum>;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_HEALTHKIT_ENTRIES: HealthKitEntry[] = [
|
||||
{ id: "bodyMass", kind: "bodyMass", direction: "bidirectional", enabled: true },
|
||||
{ id: "bp", kind: "bloodPressure", direction: "bidirectional", enabled: true },
|
||||
{ id: "glucose", kind: "bloodGlucose", direction: "bidirectional", enabled: true },
|
||||
{ id: "heartRate", kind: "heartRate", direction: "readOnly", enabled: true },
|
||||
{ id: "stepCount", kind: "stepCount", direction: "readOnly", enabled: true },
|
||||
{ id: "sleep", kind: "sleepAnalysis", direction: "readOnly", enabled: true },
|
||||
];
|
||||
|
||||
interface StoredConfig {
|
||||
entries: HealthKitEntry[];
|
||||
}
|
||||
|
||||
function parseStored(json: unknown): StoredConfig | null {
|
||||
if (!json || typeof json !== "object") return null;
|
||||
const obj = json as Record<string, unknown>;
|
||||
const entries = obj.entries;
|
||||
if (!Array.isArray(entries)) return null;
|
||||
const out: HealthKitEntry[] = [];
|
||||
for (const raw of entries) {
|
||||
if (!raw || typeof raw !== "object") continue;
|
||||
const e = raw as Record<string, unknown>;
|
||||
const id = typeof e.id === "string" ? e.id : null;
|
||||
const kind = typeof e.kind === "string" ? e.kind : id;
|
||||
const directionRaw = typeof e.direction === "string" ? e.direction : null;
|
||||
if (!id || !kind || !directionRaw) continue;
|
||||
const dir = directionEnum.safeParse(directionRaw);
|
||||
if (!dir.success) continue;
|
||||
out.push({
|
||||
id,
|
||||
kind,
|
||||
direction: dir.data,
|
||||
enabled: typeof e.enabled === "boolean" ? e.enabled : true,
|
||||
});
|
||||
}
|
||||
return { entries: out };
|
||||
}
|
||||
|
||||
function mergeWithDefaults(stored: StoredConfig | null): HealthKitEntry[] {
|
||||
const map = new Map<string, HealthKitEntry>();
|
||||
for (const def of DEFAULT_HEALTHKIT_ENTRIES) {
|
||||
map.set(def.id, { ...def });
|
||||
}
|
||||
if (stored) {
|
||||
for (const entry of stored.entries) {
|
||||
const existing = map.get(entry.id);
|
||||
if (existing) {
|
||||
map.set(entry.id, { ...existing, ...entry });
|
||||
} else {
|
||||
// Surface custom keys the user has added.
|
||||
map.set(entry.id, { ...entry, enabled: entry.enabled ?? true });
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...map.values()];
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "integrations.healthkit.get" } });
|
||||
|
||||
const row = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: { healthKitConfigJson: true, healthKitLastSyncedAt: true },
|
||||
});
|
||||
|
||||
const stored = parseStored(row?.healthKitConfigJson ?? null);
|
||||
const entries = mergeWithDefaults(stored);
|
||||
|
||||
return apiSuccess({
|
||||
entries,
|
||||
lastSyncedAt: row?.healthKitLastSyncedAt?.toISOString() ?? null,
|
||||
});
|
||||
});
|
||||
|
||||
export const PATCH = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const { data: body, error } = await safeJson(request);
|
||||
if (error) return error;
|
||||
|
||||
const parsed = patchSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const row = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: { healthKitConfigJson: true },
|
||||
});
|
||||
const stored = parseStored(row?.healthKitConfigJson ?? null);
|
||||
|
||||
// Resolve known ids set: default ids + already-stored ids.
|
||||
const knownIds = new Set<string>(
|
||||
DEFAULT_HEALTHKIT_ENTRIES.map((e) => e.id),
|
||||
);
|
||||
if (stored) for (const e of stored.entries) knownIds.add(e.id);
|
||||
|
||||
// Merge by id; unknown ids are silently ignored per spec.
|
||||
const map = new Map<string, HealthKitEntry>();
|
||||
if (stored) for (const e of stored.entries) map.set(e.id, e);
|
||||
for (const update of parsed.data.entries) {
|
||||
if (!knownIds.has(update.id)) continue;
|
||||
const existing =
|
||||
map.get(update.id) ??
|
||||
DEFAULT_HEALTHKIT_ENTRIES.find((d) => d.id === update.id);
|
||||
map.set(update.id, {
|
||||
id: update.id,
|
||||
kind: update.kind ?? existing?.kind ?? update.id,
|
||||
direction: update.direction,
|
||||
enabled: update.enabled ?? existing?.enabled ?? true,
|
||||
});
|
||||
}
|
||||
|
||||
const updatedConfig: StoredConfig = { entries: [...map.values()] };
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
healthKitConfigJson: updatedConfig as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog("integrations.healthkit.update", {
|
||||
userId: user.id,
|
||||
details: { count: updatedConfig.entries.length },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: { name: "integrations.healthkit.update" },
|
||||
meta: { count: updatedConfig.entries.length },
|
||||
});
|
||||
|
||||
// Return resolved config (defaults merged) so the client always sees a
|
||||
// complete entries list.
|
||||
const merged = mergeWithDefaults(updatedConfig);
|
||||
return apiSuccess({
|
||||
entries: merged,
|
||||
lastSyncedAt: null,
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user