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>
69 lines
2.3 KiB
TypeScript
69 lines
2.3 KiB
TypeScript
import type { Route } from "./+types/api.v1.routes._index";
|
|
import { requireApiUser, apiError, apiJson } from "~/lib/api-guard.server";
|
|
import { listRoutes, createRoute } from "~/lib/routes.server";
|
|
import {
|
|
PaginationQuerySchema,
|
|
CreateRouteRequestSchema,
|
|
ERROR_CODES,
|
|
zodIssuesToFieldErrors,
|
|
RouteListResponseSchema,
|
|
CreateRouteResponseSchema,
|
|
} from "@trails-cool/api";
|
|
|
|
/** GET /api/v1/routes — paginated route list */
|
|
export async function loader({ request }: Route.LoaderArgs) {
|
|
const user = await requireApiUser(request);
|
|
const url = new URL(request.url);
|
|
const query = PaginationQuerySchema.safeParse({
|
|
cursor: url.searchParams.get("cursor") ?? undefined,
|
|
limit: url.searchParams.get("limit") ?? undefined,
|
|
});
|
|
if (!query.success) {
|
|
return apiError(400, ERROR_CODES.VALIDATION_ERROR, "Invalid pagination params");
|
|
}
|
|
|
|
const allRoutes = await listRoutes(user.id);
|
|
const { cursor, limit } = query.data;
|
|
|
|
let startIdx = 0;
|
|
if (cursor) {
|
|
const idx = allRoutes.findIndex((r) => r.id === cursor);
|
|
startIdx = idx >= 0 ? idx + 1 : 0;
|
|
}
|
|
|
|
const page = allRoutes.slice(startIdx, startIdx + limit);
|
|
const nextCursor = startIdx + limit < allRoutes.length ? page[page.length - 1]?.id ?? null : null;
|
|
|
|
return apiJson(RouteListResponseSchema, {
|
|
routes: page.map((r) => ({
|
|
id: r.id,
|
|
name: r.name,
|
|
description: r.description ?? "",
|
|
distance: r.distance,
|
|
elevationGain: r.elevationGain,
|
|
elevationLoss: r.elevationLoss,
|
|
routingProfile: r.routingProfile,
|
|
dayBreaks: r.dayBreaks ?? [],
|
|
geojson: r.geojson,
|
|
createdAt: r.createdAt.toISOString(),
|
|
updatedAt: r.updatedAt.toISOString(),
|
|
})),
|
|
nextCursor,
|
|
});
|
|
}
|
|
|
|
/** POST /api/v1/routes — create a new route */
|
|
export async function action({ request }: Route.ActionArgs) {
|
|
if (request.method !== "POST") return new Response(null, { status: 405 });
|
|
const user = await requireApiUser(request);
|
|
|
|
const body = await request.json().catch(() => null);
|
|
const parsed = CreateRouteRequestSchema.safeParse(body);
|
|
if (!parsed.success) {
|
|
return apiError(400, ERROR_CODES.VALIDATION_ERROR, "Validation failed",
|
|
zodIssuesToFieldErrors(parsed.error));
|
|
}
|
|
|
|
const id = await createRoute(user.id, parsed.data);
|
|
return apiJson(CreateRouteResponseSchema, { id }, { status: 201 });
|
|
}
|