trails/apps/journal/app/routes/api.v1.routes.test.ts
Ullrich Schäfer 61a2d0085b
one source of truth for Route/Activity shapes; enforce api contracts
Route and Activity existed three times: hand-written interfaces in
packages/types, Zod contracts in packages/api, and Drizzle columns in
packages/db — each with different fields and nullability. The
hand-written ones had drifted so far they had zero importers; the Zod
contracts were advisory because v1 handlers hand-rolled Response.json
shapes nothing validated.

- packages/types keeps only what both apps actually share (Waypoint,
  WaypointPoiTags) and documents where row types and wire contracts
  live; the dead Route/RouteMetadata/RouteVersion/Activity interfaces
  are gone
- packages/db exports canonical inferred row types (RouteRow,
  ActivityRow, RouteVersionRow, UserRow)
- packages/api contracts are reconciled with the real wire format
  (RouteVersionSchema gains the id and createdBy fields the endpoint
  has always returned) and gain Create*ResponseSchemas
- apiJson(schema, payload) in api-guard parses every v1 response
  through its contract: drift is now a thrown ZodError in tests/CI,
  unknown keys are stripped, and payloads are compile-checked as
  z.input of the schema

Enforcement immediately caught two real drifts: nullable DB
descriptions could ship null where the contract promises string (now
coalesced at the boundary), and GET /api/v1/activities/:id was missing
the routeName and photos fields its contract declares.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 07:39:50 +02:00

173 lines
6.1 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from "vitest";
import { TERMS_VERSION } from "~/lib/legal";
const mockUser = { id: "user-1", email: "test@test.com", username: "test", domain: "localhost", displayName: null, bio: null, createdAt: new Date(), termsVersion: TERMS_VERSION };
const ROUTE_ID = "11111111-1111-4111-8111-111111111111";
const VERSION_ID = "22222222-2222-4222-8222-222222222222";
const NEW_ID = "33333333-3333-4333-8333-333333333333";
const mockGetAuthenticatedUser = vi.fn();
const mockListRoutes = vi.fn();
const mockCreateRoute = vi.fn();
const mockGetRouteWithVersions = vi.fn();
const mockGetRoute = vi.fn();
const mockDeleteRoute = vi.fn();
vi.mock("~/lib/db", () => ({ getDb: vi.fn() }));
vi.mock("~/lib/auth.server", () => ({ getSessionUser: vi.fn() }));
vi.mock("~/lib/oauth.server", async (importOriginal) => {
const actual = await importOriginal<typeof import("~/lib/oauth.server")>();
return { ...actual, getAuthenticatedUser: mockGetAuthenticatedUser };
});
vi.mock("~/lib/routes.server", () => ({
listRoutes: mockListRoutes,
createRoute: mockCreateRoute,
getRouteWithVersions: mockGetRouteWithVersions,
getRoute: mockGetRoute,
updateRoute: vi.fn(),
deleteRoute: mockDeleteRoute,
}));
function authRequest(path: string, init?: RequestInit) {
return new Request(`http://localhost:3000${path}`, {
...init,
headers: {
Authorization: "Bearer valid-token",
"Content-Type": "application/json",
...(init?.headers as Record<string, string> ?? {}),
},
});
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function routeArgs(request: Request, params: Record<string, string>, pattern: string): any {
return { request, params, context: {}, unstable_url: new URL(request.url), unstable_pattern: pattern };
}
beforeEach(() => {
vi.clearAllMocks();
mockGetAuthenticatedUser.mockResolvedValue(mockUser);
});
describe("GET /api/v1/routes", () => {
it("returns paginated routes", async () => {
const now = new Date();
mockListRoutes.mockResolvedValue([
{
id: ROUTE_ID, name: "Tour", description: "", distance: 42000,
elevationGain: 340, elevationLoss: 320, routingProfile: "fastbike",
dayBreaks: [], geojson: null, ownerId: "user-1", gpx: null,
tags: null, plannerState: null, createdAt: now, updatedAt: now,
},
]);
const { loader } = await import("./api.v1.routes._index.ts");
const resp = await loader(routeArgs(authRequest("/api/v1/routes"), {}, "api/v1/routes")) as Response;
const data = await resp.json();
expect(data.routes).toHaveLength(1);
expect(data.routes[0].id).toBe(ROUTE_ID);
expect(data.nextCursor).toBeNull();
});
it("returns 401 without auth", async () => {
mockGetAuthenticatedUser.mockResolvedValue(null);
const { loader } = await import("./api.v1.routes._index.ts");
try {
await loader(routeArgs(new Request("http://localhost:3000/api/v1/routes"), {}, "api/v1/routes"));
expect.fail("should throw");
} catch (err) {
expect(err).toBeInstanceOf(Response);
expect((err as Response).status).toBe(401);
}
});
});
describe("POST /api/v1/routes", () => {
it("creates a route with valid body", async () => {
mockCreateRoute.mockResolvedValue(NEW_ID);
const { action } = await import("./api.v1.routes._index.ts");
const resp = await action(routeArgs(
authRequest("/api/v1/routes", {
method: "POST",
body: JSON.stringify({ name: "New Route" }),
}), {}, "api/v1/routes",
)) as Response;
expect(resp.status).toBe(201);
const data = await resp.json();
expect(data.id).toBe(NEW_ID);
});
it("returns 400 on validation error", async () => {
const { action } = await import("./api.v1.routes._index.ts");
const resp = await action(routeArgs(
authRequest("/api/v1/routes", {
method: "POST",
body: JSON.stringify({ name: "" }),
}), {}, "api/v1/routes",
)) as Response;
expect(resp.status).toBe(400);
const data = await resp.json();
expect(data.code).toBe("VALIDATION_ERROR");
});
});
describe("GET /api/v1/routes/:id", () => {
it("returns route detail", async () => {
const now = new Date();
mockGetRouteWithVersions.mockResolvedValue({
id: ROUTE_ID, name: "Tour", description: "", distance: 42000,
elevationGain: 340, elevationLoss: 320, routingProfile: "fastbike",
dayBreaks: [], gpx: "<gpx/>", ownerId: "user-1",
tags: null, plannerState: null, createdAt: now, updatedAt: now,
versions: [{ id: VERSION_ID, routeId: ROUTE_ID, version: 1, gpx: "<gpx/>", createdBy: "user-1", changeDescription: null, createdAt: now }],
});
const { loader } = await import("./api.v1.routes.$id.ts");
const resp = await loader(routeArgs(
authRequest(`/api/v1/routes/${ROUTE_ID}`), { id: ROUTE_ID }, "api/v1/routes/:id",
)) as Response;
const data = await resp.json();
expect(data.id).toBe(ROUTE_ID);
expect(data.gpx).toBe("<gpx/>");
expect(data.versions).toHaveLength(1);
});
it("returns 404 for missing route", async () => {
mockGetRouteWithVersions.mockResolvedValue(null);
const { loader } = await import("./api.v1.routes.$id.ts");
const resp = await loader(routeArgs(
authRequest("/api/v1/routes/missing"), { id: "missing" }, "api/v1/routes/:id",
)) as Response;
expect(resp.status).toBe(404);
});
});
describe("DELETE /api/v1/routes/:id", () => {
it("returns 204 on success", async () => {
mockGetRoute.mockResolvedValue({ id: "r1", ownerId: "user-1" });
mockDeleteRoute.mockResolvedValue(true);
const { action } = await import("./api.v1.routes.$id.ts");
const resp = await action(routeArgs(
authRequest("/api/v1/routes/r1", { method: "DELETE" }), { id: "r1" }, "api/v1/routes/:id",
)) as Response;
expect(resp.status).toBe(204);
});
it("returns 404 if not found", async () => {
mockGetRoute.mockResolvedValue(null);
const { action } = await import("./api.v1.routes.$id.ts");
const resp = await action(routeArgs(
authRequest("/api/v1/routes/missing", { method: "DELETE" }), { id: "missing" }, "api/v1/routes/:id",
)) as Response;
expect(resp.status).toBe(404);
});
});