All files / routes/homeowner favorites.routes.ts

93.26% Statements 97/104
95% Branches 38/40
92.3% Functions 12/13
93.2% Lines 96/103

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209                    1x       38x     1x         1x 1x 1x 1x 1x   1x           1x 11x 11x 11x 11x 11x 11x         11x 11x         11x 2x 2x 1x     10x                           10x     8x 5x 5x     10x 7x   3x 3x       3x 3x   3x 6x 5x 5x   3x       1x 7x 7x 7x 7x 4x   3x 3x 1x   2x 2x     2x 2x 2x 2x       1x 7x 7x 7x 7x 2x   5x 5x 1x       4x   159x   4x 4x 4x 4x       1x 5x 5x 5x 5x 5x 5x       1x                     1x 2x 2x 2x 2x 2x 2x                 1x                 1x 6x 6x 6x 6x 1x   5x 5x     5x 5x 5x 5x        
import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
import { createDal } from "../../dal";
import { getDb } from "../../db";
import { success } from "../../lib/response";
 
type HoUser = { id: string; name: string; email: string };
type Variables = { hoUser: HoUser | null; };
 
const app = new Hono<{ Bindings: CloudflareBindings; Variables: Variables }>();
 
// Middleware guarantees hoUser is set; this avoids noNonNullAssertion lint
function getUser(c: { get(key: "hoUser"): HoUser | null }): HoUser {
	return c.get("hoUser") as HoUser;
}
 
const entityTypes = ["pro", "project", "room", "photo"] as const;
// Entity ids in this codebase are cuid2 (24 chars) or short numeric. 128 is a
// generous ceiling that still stops abuse. Without a max, the bulk endpoint
// would accept up to 500 items * unbounded string length = multi-MB requests
// that pass Zod validation and hit D1.
const MAX_ENTITY_ID_LEN = 128;
const MAX_LIST_LIMIT = 100;
const DEFAULT_LIST_LIMIT = 20;
const entityTypeEnum = z.enum(entityTypes);
const entityIdSchema = z.string().min(1).max(MAX_ENTITY_ID_LEN);
 
const addFavoriteSchema = z.object({
	entityType: entityTypeEnum,
	entityId: entityIdSchema,
});
 
// GET /api/homeowner/favorites
app.get("/", async (c) => {
	const user = getUser(c);
	const type = c.req.query("type");
	const limitParam = c.req.query("limit");
	const cursor = c.req.query("cursor");
	const db = getDb(c.env.DB);
	const dal = createDal(db);
 
	// Clamp to avoid a caller forcing D1 to return an unbounded page (e.g.
	// ?limit=999999) which wastes Worker CPU and risks timeouts on large
	// accounts.
	const parsedLimit = limitParam ? parseInt(limitParam, 10) : DEFAULT_LIST_LIMIT;
	const limit = Math.min(
		Math.max(Number.isNaN(parsedLimit) ? DEFAULT_LIST_LIMIT : parsedLimit, 1),
		MAX_LIST_LIMIT,
	);
	// Validate optional type filter against the enum if present.
	if (type !== undefined) {
		const parsed = entityTypeEnum.safeParse(type);
		if (!parsed.success) {
			return c.json({ error: "Invalid entity type" }, 400);
		}
	}
	const result = await dal.hoFavorites.findByUserPaginated(user.id, {
		limit,
		cursor: cursor || undefined,
		entityType: type || undefined,
	});
 
	// Photo favorites store the media row id as entityId. The /account/favorites
	// SSR consumer needs both the parent roomId (to fetch the room's enriched
	// shape) and the photo's storageKey (to override the room's cover with the
	// favorited photo). Resolve both here so the page can render photo tiles
	// without an extra round-trip per item. Mirrors mood-boards.routes.ts:154-179
	// — without this, the page silently drops photo favorites.
	// Enrich only the page being returned; do not pre-fetch beyond `data` or
	// the cursor semantics get distorted.
	const photoEntityIds = Array.from(
		new Set(
			result.data
				.filter((row) => row.entityType === "photo")
				.map((row) => Number.parseInt(row.entityId, 10))
				.filter((n) => Number.isFinite(n) && n > 0),
		),
	);
	if (photoEntityIds.length === 0) {
		return success(c, result);
	}
	const mediaRows = await dal.media.findByIds(photoEntityIds);
	const photoMediaMap = new Map<
		number,
		{ roomId: number; storageKey: string }
	>();
	for (const m of mediaRows) {
		photoMediaMap.set(m.id, { roomId: m.roomId, storageKey: m.storageKey });
	}
	const enrichedData = result.data.map((row) => {
		if (row.entityType !== "photo") return row;
		const meta = photoMediaMap.get(Number.parseInt(row.entityId, 10));
		return { ...row, photoMeta: meta ?? null };
	});
	return success(c, { ...result, data: enrichedData });
});
 
// GET /api/homeowner/favorites/check
app.get("/check", async (c) => {
	const user = getUser(c);
	const type = c.req.query("type");
	const id = c.req.query("id");
	if (!type || !id) {
		return c.json({ error: "type and id are required" }, 400);
	}
	const typeParsed = entityTypeEnum.safeParse(type);
	if (!typeParsed.success) {
		return c.json({ error: "Invalid entity type" }, 400);
	}
	const idParsed = entityIdSchema.safeParse(id);
	Iif (!idParsed.success) {
		return c.json({ error: "Invalid entity id" }, 400);
	}
	const db = getDb(c.env.DB);
	const dal = createDal(db);
	const isFavorited = await dal.hoFavorites.check(user.id, typeParsed.data, idParsed.data);
	return success(c, { favorited: isFavorited });
});
 
// GET /api/homeowner/favorites/check-batch
app.get("/check-batch", async (c) => {
	const user = getUser(c);
	const type = c.req.query("type");
	const idsParam = c.req.query("ids");
	if (!type || !idsParam) {
		return c.json({ error: "type and ids are required" }, 400);
	}
	const typeParsed = entityTypeEnum.safeParse(type);
	if (!typeParsed.success) {
		return c.json({ error: "Invalid entity type" }, 400);
	}
	// Cap list length AND per-id length so a 100-item batch with oversized
	// ids can't be used to send a huge query string.
	const ids = idsParam
		.split(",")
		.filter((id) => id.length > 0 && id.length <= MAX_ENTITY_ID_LEN)
		.slice(0, 100);
	const db = getDb(c.env.DB);
	const dal = createDal(db);
	const favoritedSet = await dal.hoFavorites.checkBatch(user.id, typeParsed.data, ids);
	return success(c, { favorited: Array.from(favoritedSet) });
});
 
// POST /api/homeowner/favorites
app.post("/", zValidator("json", addFavoriteSchema), async (c) => {
	const user = getUser(c);
	const { entityType, entityId } = c.req.valid("json");
	const db = getDb(c.env.DB);
	const dal = createDal(db);
	await dal.hoFavorites.add(user.id, entityType, entityId);
	return success(c, { added: true }, 201);
});
 
// POST /api/homeowner/favorites/bulk
const bulkSchema = z.object({
	items: z
		.array(
			z.object({
				entityType: entityTypeEnum,
				entityId: entityIdSchema,
			}),
		)
		.max(500, "Too many items — max 500 per bulk request"),
});
 
app.post("/bulk", zValidator("json", bulkSchema), async (c) => {
	const user = getUser(c);
	const { items } = c.req.valid("json");
	const db = getDb(c.env.DB);
	const dal = createDal(db);
	const result = await dal.hoFavorites.bulkCreate(user.id, items);
	return success(c, result, 201);
});
 
// GET /api/homeowner/favorites/by-room-type
//
// Returns this user's room favorites grouped by roomType, sorted by count
// DESC. Powers the /account hub activity bar's rule 2 ("you saved 5
// kitchen photos — see all"). Empty array when the user has no room
// favorites; the hub treats that as "fall through to rule 3".
app.get("/by-room-type", async (c) => {
	const user = getUser(c);
	const db = getDb(c.env.DB);
	const dal = createDal(db);
	const result = await dal.hoFavorites.countByRoomType(user.id);
	return success(c, result);
});
 
// DELETE /api/homeowner/favorites/:entityType/:entityId
app.delete("/:entityType/:entityId", async (c) => {
	const user = getUser(c);
	const { entityType, entityId } = c.req.param();
	const typeParsed = entityTypeEnum.safeParse(entityType);
	if (!typeParsed.success) {
		return c.json({ error: "Invalid entity type" }, 400);
	}
	const idParsed = entityIdSchema.safeParse(entityId);
	Iif (!idParsed.success) {
		return c.json({ error: "Invalid entity id" }, 400);
	}
	const db = getDb(c.env.DB);
	const dal = createDal(db);
	await dal.hoFavorites.remove(user.id, typeParsed.data, idParsed.data);
	return success(c, { removed: true });
});
 
export default app;