All files / routes/marketplace room-categories.ts

100% Statements 44/44
95.65% Branches 22/23
100% Functions 4/4
100% Lines 42/42

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                          1x     1x 12x 12x 12x 12x   12x         10x 9x 1x                     8x                 8x                         8x 1x       7x 7x 7x 7x 7x       8x 7x     7x                           7x 7x 7x 7x         7x   7x         10x 10x 7x       7x 6x 6x 3x         7x 6x 6x 1x         8x                     10x   2x          
// Room Categories Endpoint - Returns all room categories with cover images and project counts
import { Hono } from "hono";
import { and, inArray, sql } from "drizzle-orm";
import { handleError, success } from "../../lib/response";
import { CACHE_KEYS, CACHE_TTL } from "../../lib/cache";
import type { ContextVariables } from "../../middleware";
import * as schema from "../../db/schema";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: ContextVariables;
};
 
const roomCategories = new Hono<Env>();
 
// GET /api/marketplace/room-categories — all room categories with stats
roomCategories.get("/", async (c) => {
	try {
		const dal = c.get("dal");
		const db = c.get("db");
		const cache = c.get("cache");
 
		const data = await cache.getOrSet(
			CACHE_KEYS.MARKETPLACE_ROOM_CATEGORIES,
			async () => {
				// Quick guard: no published pros means no rooms either.
				const publishedProIds =
					await dal.pros.findIdsByStatus("published");
				if (publishedProIds.length === 0) {
					return [];
				}
 
				// Constrain rooms to those whose project belongs to a
				// published pro via a correlated EXISTS subquery — the prior
				// implementation materialized every published project ID
				// into an `inArray()` bind list which, combined with the
				// `roomType IN (...)` list below, blew past D1's 100-parameter
				// statement limit once the catalog grew. Mirrors the
				// predicate used by /api/marketplace/homepage (PR #400) and
				// /api/marketplace/rooms (PR #403).
				const publishedProjectExists = sql`EXISTS (
					SELECT 1 FROM ${schema.projects}
					INNER JOIN ${schema.pros} ON ${schema.pros.id} = ${schema.projects.proId}
					WHERE ${schema.projects.id} = ${schema.rooms.projectId}
					  AND ${schema.projects.status} = 'published'
					  AND ${schema.pros.status} = 'published'
				)`;
 
				// Get room type stats in parallel with room type labels
				const [roomStats, allRoomTypes] = await Promise.all([
					db
						.select({
							roomType: schema.rooms.roomType,
							projectCount:
								sql<number>`count(distinct ${schema.rooms.projectId})`,
						})
						.from(schema.rooms)
						.where(publishedProjectExists)
						.groupBy(schema.rooms.roomType),
					db.select().from(schema.roomTypes),
				]);
 
				if (roomStats.length === 0) {
					return [];
				}
 
				// Build label and icon lookup maps
				const roomTypeLabelMap = new Map<string, string>();
				const roomTypeIconMap = new Map<string, string | null>();
				for (const rt of allRoomTypes) {
					roomTypeLabelMap.set(rt.code, rt.displayName);
					roomTypeIconMap.set(rt.code, rt.icon);
				}
 
				// Get cover images for each room type
				const roomTypeCodes = roomStats.map((rs) => rs.roomType);
				const coverByRoomType = new Map<string, string | null>();
 
				// Get one room per room type from published projects
				const sampleRooms = await db
					.select({
						id: schema.rooms.id,
						roomType: schema.rooms.roomType,
					})
					.from(schema.rooms)
					.where(
						and(
							inArray(schema.rooms.roomType, roomTypeCodes),
							publishedProjectExists,
						),
					);
 
				// Pick one room ID per room type
				const sampleRoomByType = new Map<string, number>();
				for (const room of sampleRooms) {
					Eif (!sampleRoomByType.has(room.roomType)) {
						sampleRoomByType.set(room.roomType, room.id);
					}
				}
 
				// Fetch media for the sample rooms
				const sampleRoomIds = Array.from(sampleRoomByType.values());
				const sampleMedia =
					sampleRoomIds.length > 0
						? await dal.media.findByRoomIds(sampleRoomIds)
						: [];
 
				// Map room type -> cover image (prefer isCover, fallback to first)
				const roomIdToType = new Map<number, string>();
				for (const [type, roomId] of sampleRoomByType) {
					roomIdToType.set(roomId, type);
				}
 
				// First pass: collect covers marked as isCover
				for (const m of sampleMedia) {
					const type = roomIdToType.get(m.roomId);
					if (type && m.isCover && !coverByRoomType.has(type)) {
						coverByRoomType.set(type, m.storageKey);
					}
				}
 
				// Second pass: fallback to first media for types without an explicit cover
				for (const m of sampleMedia) {
					const type = roomIdToType.get(m.roomId);
					if (type && !coverByRoomType.has(type)) {
						coverByRoomType.set(type, m.storageKey);
					}
				}
 
				// Assemble response
				return roomStats.map((rs) => ({
					value: rs.roomType,
					label: roomTypeLabelMap.get(rs.roomType) ?? rs.roomType,
					icon: roomTypeIconMap.get(rs.roomType) ?? null,
					coverImage: coverByRoomType.get(rs.roomType) ?? null,
					projectCount: rs.projectCount,
				}));
			},
			{ l1Ttl: CACHE_TTL.MARKETPLACE_ROOM_CATEGORIES_L1, l2Ttl: CACHE_TTL.MARKETPLACE_ROOM_CATEGORIES_L2 },
		);
 
		return success(c, data);
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default roomCategories;