trails/apps/journal/app/routes/api.v1.routes.$id.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

70 lines
2.5 KiB
TypeScript

import type { Route } from "./+types/api.v1.routes.$id";
import { requireApiUser, apiError, apiJson } from "~/lib/api-guard.server";
import { getRouteWithVersions, updateRoute, deleteRoute } from "~/lib/routes.server";
import { loadOwnedRoute } from "~/lib/ownership.server";
import { UpdateRouteRequestSchema, ERROR_CODES, zodIssuesToFieldErrors, RouteDetailSchema } from "@trails-cool/api";
/** GET /api/v1/routes/:id — full route detail */
export async function loader({ request, params }: Route.LoaderArgs) {
const user = await requireApiUser(request);
const route = await getRouteWithVersions(params.id);
if (!route || route.ownerId !== user.id) {
return apiError(404, ERROR_CODES.NOT_FOUND, "Route not found");
}
return apiJson(RouteDetailSchema, {
id: route.id,
name: route.name,
description: route.description ?? "",
distance: route.distance,
elevationGain: route.elevationGain,
elevationLoss: route.elevationLoss,
routingProfile: route.routingProfile,
dayBreaks: route.dayBreaks ?? [],
gpx: route.gpx,
geojson: null, // TODO: fetch geojson
versions: route.versions.map((v) => ({
id: v.id,
version: v.version,
createdBy: v.createdBy,
changeDescription: v.changeDescription,
createdAt: v.createdAt.toISOString(),
})),
createdAt: route.createdAt.toISOString(),
updatedAt: route.updatedAt.toISOString(),
});
}
/** PUT /api/v1/routes/:id — update a route */
/** DELETE /api/v1/routes/:id — delete a route */
export async function action({ request, params }: Route.ActionArgs) {
const user = await requireApiUser(request);
if (request.method === "PUT") {
const body = await request.json().catch(() => null);
const parsed = UpdateRouteRequestSchema.safeParse(body);
if (!parsed.success) {
return apiError(400, ERROR_CODES.VALIDATION_ERROR, "Validation failed",
zodIssuesToFieldErrors(parsed.error));
}
const result = await loadOwnedRoute(params.id, user.id);
if (!result.ok) {
return apiError(404, ERROR_CODES.NOT_FOUND, "Route not found");
}
await updateRoute(result.entity, parsed.data);
return Response.json({ ok: true });
}
if (request.method === "DELETE") {
const result = await loadOwnedRoute(params.id, user.id);
if (!result.ok) {
return apiError(404, ERROR_CODES.NOT_FOUND, "Route not found");
}
await deleteRoute(result.entity);
return new Response(null, { status: 204 });
}
return new Response(null, { status: 405 });
}