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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | 1x 1x 1x 15x 15x 15x 15x 15x 2x 15x 1x 15x 1x 15x 2x 15x 2x 15x 15x 5x 10x 9x 9x 9x 9x 9x 9x 9x 10x 9x 9x 9x 9x 9x 7x 9x 9x 15x 15x 7x 9x 7x 9x 15x 15x 1x 9x 9x 15x 15x 6x 9x 9x 1x 8x 8x 8x 9x 1x 1x 12x 12x 12x 12x 12x 11x 1x 10x 10x 2x 8x 8x 2x 6x 6x 9x 6x 6x 12x 12x 3x 3x 3x 6x 3x 12x 12x 6x 6x 6x 2x 2x 6x 6x 2x 2x 6x 12x 12x 12x 3x 3x 1x 3x 12x 12x 1x 1x 6x 6x 6x 6x 6x 6x 2x 4x 4x 1x 3x 3x 1x 2x 2x 1x 1x 2x 6x 1x 6x | // Public Marketplace Rooms Routes (API Key Protected)
import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
import { inArray, eq } from "drizzle-orm";
import { handleError, success, successWithPagination } from "../../lib/response";
import { buildPaginationMeta } from "../../lib/utils";
import type { ContextVariables } from "../../middleware";
import * as schema from "../../db/schema";
type Env = {
Bindings: CloudflareBindings;
Variables: ContextVariables;
};
const querySchema = z.object({
roomType: z.string().optional(),
page: z.coerce.number().default(1),
limit: z.coerce.number().default(12),
styleTags: z.string().optional(),
budgetRanges: z.string().optional(),
materials: z.string().optional(),
propertyTypes: z.string().optional(),
});
const rooms = new Hono<Env>();
// List published rooms with filters and pagination
// Only shows rooms from published projects of published pros
// Only returns rooms that have at least one media item
rooms.get("/", zValidator("query", querySchema), async (c) => {
try {
const dal = c.get("dal");
const db = c.get("db");
const { page, limit, roomType, styleTags, budgetRanges, materials, propertyTypes } =
c.req.valid("query");
// Parse comma-separated filter params
const roomTypeCodes = roomType
? roomType.split(",").map((s) => s.trim()).filter(Boolean)
: undefined;
const styleTagCodes = styleTags
? styleTags.split(",").map((s) => s.trim()).filter(Boolean)
: undefined;
const budgetRangeValues = budgetRanges
? budgetRanges.split(",").map((s) => s.trim()).filter(Boolean)
: undefined;
const materialCodes = materials
? materials.split(",").map((s) => s.trim()).filter(Boolean)
: undefined;
const propertyTypeValues = propertyTypes
? propertyTypes.split(",").map((s) => s.trim()).filter(Boolean)
: undefined;
// Fetch rooms with filters (paginated). The published/visibility
// constraint (rooms belong to published projects of published pros)
// and the propertyType filter are both resolved inside
// findPublishedRooms via a correlated EXISTS subquery — no need to
// pre-fetch project or pro IDs, which previously materialized an
// unbounded `inArray()` bind list that could exceed D1's 100-param
// statement limit once the catalog grew past ~80 published projects.
const { rooms: roomsData, total } = await dal.rooms.findPublishedRooms(
{
roomTypes: roomTypeCodes,
styleTags: styleTagCodes,
budgetRanges: budgetRangeValues,
materials: materialCodes,
propertyTypes: propertyTypeValues,
},
page,
limit,
);
if (roomsData.length === 0) {
return successWithPagination(c, [], buildPaginationMeta(total, page, limit));
}
// Step 4: Batch-fetch media for all rooms
const roomIds = roomsData.map((r) => r.id);
const allMedia = await dal.media.findByRoomIds(roomIds);
// Group media by room ID and build cover image map + count map
const mediaByRoomId = new Map<number, typeof allMedia>();
for (const m of allMedia) {
const existing = mediaByRoomId.get(m.roomId) ?? [];
existing.push(m);
mediaByRoomId.set(m.roomId, existing);
}
// Filter out rooms with no media
const roomsWithMedia = roomsData.filter(
(r) => (mediaByRoomId.get(r.id)?.length ?? 0) > 0,
);
// Step 5: Batch-fetch project data for pro info and project titles
const projectIdSet = new Set(roomsWithMedia.map((r) => r.projectId));
const projectIds = Array.from(projectIdSet);
const projectsMap = await dal.projects.findByIds(projectIds);
// Collect pro IDs from projects
const proIdSet = new Set<string>();
for (const project of projectsMap.values()) {
proIdSet.add(project.proId);
}
const proIds = Array.from(proIdSet);
// Batch-fetch pros
const prosData =
proIds.length > 0
? await db
.select()
.from(schema.pros)
.where(inArray(schema.pros.id, proIds))
: [];
const prosMap = new Map<string, (typeof prosData)[0]>();
for (const pro of prosData) {
prosMap.set(pro.id, pro);
}
// Batch-fetch cities for pros
const proCityIds = new Set(
prosData.filter((p) => p.cityId).map((p) => p.cityId as string),
);
const proCitiesData =
proCityIds.size > 0
? await db
.select()
.from(schema.cities)
.where(inArray(schema.cities.id, Array.from(proCityIds)))
: [];
const proCitiesMap = new Map<string, string>(); // cityId -> cityName
for (const city of proCitiesData) {
proCitiesMap.set(city.id, city.name);
}
// Step 6: Batch-fetch room type names
const roomTypeCodesToFetch = new Set(roomsWithMedia.map((r) => r.roomType));
const roomTypesData =
roomTypeCodesToFetch.size > 0
? await db
.select()
.from(schema.roomTypes)
.where(inArray(schema.roomTypes.code, Array.from(roomTypeCodesToFetch)))
: [];
const roomTypesMap = new Map<string, string>(); // code -> displayName
for (const rt of roomTypesData) {
roomTypesMap.set(rt.code, rt.displayName);
}
// Step 7: Assemble room cards
const roomCards = roomsWithMedia.map((room) => {
/* v8 ignore start -- V8 artifact: ?? fallback */
const roomMedia = mediaByRoomId.get(room.id) ?? [];
/* v8 ignore stop */
// Resolve cover image: prefer isCover, fallback to first by sortOrder
const coverMedia =
roomMedia.find((m) => m.isCover) ??
[...roomMedia].sort((a, b) => a.sortOrder - b.sortOrder)[0];
const project = projectsMap.get(room.projectId);
const pro = project ? prosMap.get(project.proId) : undefined;
return {
id: room.id,
slug: room.slug,
roomType: room.roomType,
roomTypeName: roomTypesMap.get(room.roomType) ?? room.roomType,
/* v8 ignore start -- V8 artifact: ?? null fallback */
coverImage: coverMedia?.storageKey ?? null,
/* v8 ignore stop */
mediaCount: roomMedia.length,
projectTitle: project?.title ?? null,
pro: pro
? {
id: pro.id,
businessName: pro.businessName,
city: pro.cityId ? (proCitiesMap.get(pro.cityId) ?? null) : null,
}
: null,
};
});
// DAL now enforces "room has media" at the DB level, so total and the
// returned array are always in sync. The in-memory filter above is
// defensive belt-and-suspenders; it should be a no-op.
return successWithPagination(c, roomCards, buildPaginationMeta(total, page, limit));
} catch (err) {
return handleError(c, err);
}
});
// Get full room detail by slug
// Returns 404 if room not found, or if parent project/pro is not published
rooms.get("/by-slug/:slug", async (c) => {
try {
const dal = c.get("dal");
const db = c.get("db");
const { slug } = c.req.param();
// 1. Find room by slug
const room = await dal.rooms.findBySlug(slug);
if (!room) {
return c.json({ error: "Room not found" }, 404);
}
// 2. Verify parent project is published
const project = await dal.projects.findById(room.projectId);
if (!project || project.status !== "published") {
return c.json({ error: "Room not found" }, 404);
}
// 3. Verify pro is published
const pro = await dal.pros.findById(project.proId);
if (!pro || pro.status !== "published") {
return c.json({ error: "Room not found" }, 404);
}
// 4. Fetch all media for this room
const roomMedia = await dal.media.findByRoomId(room.id);
// 5. Fetch sibling rooms (other rooms in the same project)
const allProjectRooms = await dal.rooms.findByProjectId(room.projectId);
const siblingRooms = allProjectRooms.filter((r) => r.id !== room.id);
// 6. Fetch media for sibling rooms (to get cover images and counts)
const siblingRoomIds = siblingRooms.map((r) => r.id);
const siblingMedia =
siblingRoomIds.length > 0
? await dal.media.findByRoomIds(siblingRoomIds)
: [];
// Group sibling media by room ID
const siblingMediaByRoomId = new Map<number, typeof siblingMedia>();
for (const m of siblingMedia) {
const existing = siblingMediaByRoomId.get(m.roomId) ?? [];
existing.push(m);
siblingMediaByRoomId.set(m.roomId, existing);
}
// 7. Fetch room type display names for this room and siblings
const allRoomTypeCodes = new Set([
room.roomType,
...siblingRooms.map((r) => r.roomType),
]);
/* v8 ignore start -- V8 artifact: ternary false branch; set always has room.roomType */
const roomTypesData =
allRoomTypeCodes.size > 0
? await db
.select()
.from(schema.roomTypes)
.where(inArray(schema.roomTypes.code, Array.from(allRoomTypeCodes)))
: [];
/* v8 ignore stop */
const roomTypesMap = new Map<string, string>(); // code -> displayName
for (const rt of roomTypesData) {
roomTypesMap.set(rt.code, rt.displayName);
}
// 8. Resolve locality name for project
let localityName: string | null = null;
if (project.localityId) {
const localityResult = await db
.select({ name: schema.localities.name })
.from(schema.localities)
.where(eq(schema.localities.id, project.localityId))
.limit(1);
localityName = localityResult[0]?.name ?? null;
}
// 9. Resolve city name for pro
let cityName: string | null = null;
if (pro.cityId) {
const cityResult = await db
.select({ name: schema.cities.name })
.from(schema.cities)
.where(eq(schema.cities.id, pro.cityId))
.limit(1);
cityName = cityResult[0]?.name ?? null;
}
// 10. Resolve inherited fields: use room-level if set, else fall back to project-level
const styleTags: string[] | null =
room.styleTags && room.styleTags.length > 0
? room.styleTags
: project.styleTagIds && project.styleTagIds.length > 0
? project.styleTagIds
: null;
const materials: string[] | null =
room.materials && room.materials.length > 0 ? room.materials : null;
const budgetSpent = room.budgetSpent ?? null;
// 11. Build sibling room summaries
const siblingRoomCards = siblingRooms.map((r) => {
const rMedia = siblingMediaByRoomId.get(r.id) ?? [];
const coverMedia =
rMedia.find((m) => m.isCover) ??
[...rMedia].sort((a, b) => a.sortOrder - b.sortOrder)[0];
return {
id: r.id,
slug: r.slug,
roomType: r.roomType,
roomTypeName: roomTypesMap.get(r.roomType) ?? r.roomType,
name: r.name ?? null,
coverImage: coverMedia?.storageKey ?? null,
mediaCount: rMedia.length,
};
});
// 12. Assemble full room detail response
const roomDetail = {
// Room fields
id: room.id,
slug: room.slug,
roomType: room.roomType,
roomTypeName: roomTypesMap.get(room.roomType) ?? room.roomType,
name: room.name ?? null,
areaSqft: room.areaSqft ?? null,
description: room.description ?? null,
metaTitle: room.metaTitle ?? null,
metaDescription: room.metaDescription ?? null,
// All media for this room
media: roomMedia,
// Resolved fields
styleTags,
budgetSpent,
materials,
// Parent project summary
project: {
id: project.id,
title: project.title,
slug: project.slug ?? null,
propertyType: project.propertyType ?? null,
propertySize: project.propertySize ?? null,
localityName,
},
// Pro info card
pro: {
id: pro.id,
businessName: pro.businessName,
profilePhoto: pro.logoUrl ?? null,
city: cityName,
slug: pro.slug ?? null,
},
// Sibling rooms
siblingRooms: siblingRoomCards,
};
return success(c, roomDetail);
} catch (err) {
return handleError(c, err);
}
});
// Compact card lookup by numeric room id. Used by favorites/mood-board
// enrichment, which stores room references as the integer id. Returns only
// what a card needs (title, cover, parent slugs, pro) — for full detail use
// /by-slug/:slug. Returns 404 if the parent project or pro isn't published.
rooms.get("/:id", async (c) => {
try {
const dal = c.get("dal");
const db = c.get("db");
const idParam = c.req.param("id");
const id = Number.parseInt(idParam, 10);
if (!Number.isFinite(id) || id <= 0) {
return c.json({ error: "Room not found" }, 404);
}
const room = await dal.rooms.findById(id);
if (!room) {
return c.json({ error: "Room not found" }, 404);
}
const project = await dal.projects.findById(room.projectId);
if (!project || project.status !== "published") {
return c.json({ error: "Room not found" }, 404);
}
const pro = await dal.pros.findById(project.proId);
if (!pro || pro.status !== "published") {
return c.json({ error: "Room not found" }, 404);
}
const media = await dal.media.findByRoomId(room.id);
const coverMedia =
media.find((m) => m.isCover) ??
[...media].sort((a, b) => a.sortOrder - b.sortOrder)[0];
const roomTypeRow = await db
.select({ displayName: schema.roomTypes.displayName })
.from(schema.roomTypes)
.where(eq(schema.roomTypes.code, room.roomType))
.limit(1);
const roomTypeName = roomTypeRow[0]?.displayName ?? room.roomType;
return success(c, {
id: room.id,
slug: room.slug,
roomType: room.roomType,
roomTypeName,
name: room.name,
coverImage: coverMedia?.storageKey ?? null,
mediaCount: media.length,
project: {
id: project.id,
slug: project.slug,
title: project.title,
},
pro: {
id: pro.id,
slug: pro.slug,
businessName: pro.businessName,
},
});
} catch (err) {
return handleError(c, err);
}
});
export default rooms;
|