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 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 | 1x 1x 17x 17x 1x 16x 16x 16x 16x 16x 16x 16x 16x 6x 6x 16x 16x 16x 1x 15x 14x 14x 14x 16x 16x 9x 8x 9x 7x 7x 14x 16x 9x 16x 16x 2x 2x 4x 2x 16x 16x 14x 1x 1x 5x 5x 5x 5x 5x 4x 1x 3x 1x 3x 3x 1x 1x 3x 3x 3x 3x 3x 1x 2x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 1x 5x 5x 4x 4x 1x 1x 8x 8x 8x 8x 8x 8x 8x 2x 8x 2x 1x 8x 2x 6x 6x 6x 6x 1x 5x 5x 4x 8x 8x 8x 4x 1x 1x 13x 13x 13x 13x 13x 13x 3x 1x 12x 2x 1x 12x 3x 9x 1x 9x 9x 1x 24x 1x 1x 31x 7x 24x 24x 24x 4x 24x 24x 4x 24x 24x 4x 24x 24x 3x 24x 24x 3x 24x 24x 24x 4x 4x 24x 4x 4x 24x 4x 4x 4x 4x 4x 24x 24x | // Public Marketplace Pro Routes (API Key Protected)
import { Hono } from "hono";
import {
type BusinessType,
businessTypes,
type City,
type CustomerSegment,
cities,
customerSegments,
type Locality,
localities,
type Pro,
projects,
type Zone,
zones,
} from "../../db/schema";
import { and, count, desc, eq, inArray, isNotNull } from "drizzle-orm";
import {
handleError,
success,
successWithPagination,
} from "../../lib/response";
import { NotFoundError } from "../../lib/errors";
import { getPagination, buildPaginationMeta } from "../../lib/utils";
import { type DualCache, CACHE_KEYS, CACHE_TTL, MARKETPLACE } from "../../lib/cache";
import type { ContextVariables } from "../../middleware";
import { enrichProjectsWithTaxonomy } from "./project-enrichment";
import type { getDb } from "../../db";
import { logger } from "../../lib/logger";
type Env = {
Bindings: CloudflareBindings;
Variables: ContextVariables;
};
// Allowlist of fields that can be requested via ?fields= query parameter
const PRO_ALLOWED_FIELDS = new Set([
"id",
"status",
"businessName",
"slug",
"description",
"profileImage",
"logoUrl",
"isFeatured",
"isEarlyAdopter",
"businessTypeId",
"customerSegmentId",
"serviceAreaIds",
"serviceCategoryIds",
"businessType",
"customerSegment",
"primaryLocality",
]);
const pros = new Hono<Env>();
// Extended pro type with resolved taxonomy data
type ProWithTaxonomy = Pro & {
businessType?: string | null;
customerSegment?: string | null;
primaryLocality?: {
id: string;
name: string;
zone: string;
city: string;
} | null;
};
// Cached taxonomy lookup tables (all 5 tables in one cache entry)
type TaxonomyTables = {
businessTypes: BusinessType[];
customerSegments: CustomerSegment[];
localities: Locality[];
zones: Zone[];
cities: City[];
};
/**
* Fetch up to 4 recent published-project cover images for a single pro.
* Symmetric with the batched cover-photo query the list endpoint uses; both
* surfaces should attach the same `portfolioCovers` field so consumers
* (chatgpt-app widgets, marketplace cards, etc.) see a consistent shape.
*/
async function fetchPortfolioCovers(
db: ReturnType<typeof getDb>,
proId: string,
): Promise<string[]> {
const rows = await db
.select({ coverImage: projects.coverImage })
.from(projects)
.where(
and(
eq(projects.proId, proId),
eq(projects.status, "published"),
isNotNull(projects.coverImage),
),
)
.orderBy(desc(projects.dateCreated))
.limit(4);
return rows
.map((r) => r.coverImage)
.filter((c): c is string => c !== null && c !== "");
}
// List published pros with filters and pagination
pros.get("/", async (c) => {
try {
const services = c.get("services");
const db = c.get("db");
const cache = c.get("cache");
const { page, limit } = getPagination(
Number(c.req.query("page") || 1),
Number(c.req.query("limit") || 20),
);
const filters = {
status: "published", // Only show published pros
search: c.req.query("search"),
isFeatured: c.req.query("isFeatured")
? c.req.query("isFeatured") === "true"
: undefined,
// Taxonomy filters - support both single and multi-select (comma-separated)
businessTypeId: c.req.query("businessTypeId"),
businessTypeIds: c.req.query("businessTypeIds"), // multi-select
customerSegmentId: c.req.query("customerSegmentId"),
customerSegmentIds: c.req.query("customerSegmentIds"), // multi-select
cityId: c.req.query("cityId"),
cityIds: c.req.query("cityIds"), // multi-select
localityId: c.req.query("localityId"),
// Junction-table filters (multi-select via comma-sep IDs)
serviceCategoryIds: c.req.query("serviceCategoryIds"),
materialTagIds: c.req.query("materialTagIds"),
};
// Field-selection allowlist (computed before cache key so the cache
// is keyed on the same shape the response will have).
const fieldsParam = c.req.query("fields");
const fields = fieldsParam
? fieldsParam
.split(",")
.map((f) => f.trim())
.filter((f) => PRO_ALLOWED_FIELDS.has(f))
.slice(0, 20)
: null;
// Cache key = filters + page + limit + fields. This handler runs on
// every Hyderabad SEO page (city/zone/locality/segment), each calling
// `getPros({ cityIds: 'hyderabad', limit: 200 })` — pass-18 LCP
// breakdown showed TTFB=3042ms on /interiors/hyderabad/central/abids
// driven entirely by this uncached path. 60s L1 / 5-min L2 is short
// enough that editorial changes show up quickly, long enough to
// kill the cold-path TTFB for repeat visitors and Lighthouse runs.
const cacheKey = `marketplace:pros:list:${JSON.stringify(filters)}:p${page}:l${limit}:f${fields?.join(",") ?? ""}`;
const cached = await cache.get<{
data: unknown[];
pagination: ReturnType<typeof buildPaginationMeta>;
}>(cacheKey);
if (cached) {
return successWithPagination(c, cached.data, cached.pagination);
}
const { pros: data, total } = await services.pro.list(
filters,
page,
limit,
);
// Enrich pros with taxonomy data (using cached lookups)
const enrichedPros = await enrichProsWithTaxonomy(db, data, cache);
// Fetch portfolio cover images for each pro (batched query).
//
// We deliberately do NOT apply a SQL-level LIMIT here. A flat limit like
// `proIds.length * 4` is global across the ordered result set, so a single
// prolific pro with many recent projects can consume the entire budget
// and starve older/quieter pros of any cover rows at all — that's how we
// ended up with "pro has images in DB but card shows initials".
// Instead we fetch all qualifying cover rows (already narrowed by
// proId IN (page of 20), status='published', cover_image IS NOT NULL)
// and cap at 4 per pro in-memory below. For realistic volumes (20 pros
// × tens of published projects each), this is a single cheap indexed read.
const proIds = enrichedPros.map((p) => p.id);
const coverPhotos =
proIds.length > 0
? await db
.select({
proId: projects.proId,
coverImage: projects.coverImage,
})
.from(projects)
.where(
and(
inArray(projects.proId, proIds),
eq(projects.status, "published"),
isNotNull(projects.coverImage),
),
)
.orderBy(desc(projects.dateCreated))
: [];
// Group cover images by proId, keeping the 4 most recent per pro.
const coversByProId = new Map<string, string[]>();
for (const row of coverPhotos) {
if (!row.coverImage) continue;
const existing = coversByProId.get(row.proId) ?? [];
if (existing.length < 4) {
existing.push(row.coverImage);
coversByProId.set(row.proId, existing);
}
}
// Count all published projects per pro — includes projects without a cover
// image, matching what the pro profile page shows.
const projectCountRows =
proIds.length > 0
? await db
.select({
proId: projects.proId,
count: count(),
})
.from(projects)
.where(
and(
inArray(projects.proId, proIds),
eq(projects.status, "published"),
),
)
.groupBy(projects.proId)
: [];
const countByProId = new Map(
projectCountRows.map((r) => [r.proId, r.count]),
);
// Attach portfolioCovers and projectCount to each enriched pro
const prosWithCovers = enrichedPros.map((pro) => ({
...pro,
portfolioCovers: coversByProId.get(pro.id) ?? [],
projectCount: countByProId.get(pro.id) ?? 0,
}));
// `fields` was already computed above (before the cache lookup) so
// the cache key matches the response shape. Apply the projection
// here.
const responseData = fields?.length
? prosWithCovers.map((v) => {
const picked: Record<string, unknown> = {};
for (const field of fields) {
/* v8 ignore start -- defensive guard: fields pre-filtered to allowed set */
if (field in v) {
/* v8 ignore stop */
picked[field] = v[field as keyof typeof v];
}
}
return picked;
})
: prosWithCovers;
const pagination = buildPaginationMeta(total, page, limit);
// Cache the assembled response so subsequent identical filter
// combos skip every D1 query. Awaited (not waitUntil'd) to match
// the same-file `pros.get("/:id/full", ...)` cache pattern and to
// keep the unit tests synchronous — the put is L1+L2 + a memory
// write, ~10ms, well under the 1.5s TTFB this avoids on cache hit.
await cache.put(
cacheKey,
{ data: responseData, pagination },
{
l1Ttl: CACHE_TTL.MARKETPLACE_PROS_LIST_L1,
l2Ttl: CACHE_TTL.MARKETPLACE_PROS_LIST_L2,
},
);
return successWithPagination(c, responseData, pagination);
} catch (err) {
return handleError(c, err);
}
});
// Get single published pro by slug
pros.get("/by-slug/:slug", async (c) => {
try {
const services = c.get("services");
const db = c.get("db");
const cache = c.get("cache");
const pro = await services.pro.getBySlug(c.req.param("slug"));
// Only return if pro is published
if (pro.status !== "published") {
return c.json({ error: "Pro not found" }, 404);
}
// Increment view count (fire and forget - don't block response)
services.pro.incrementViewCount(pro.id).catch((err) => {
logger.error("Failed to increment view count:", err);
});
// Enrich + attach portfolio covers in parallel.
const [[enrichedPro], portfolioCovers] = await Promise.all([
enrichProsWithTaxonomy(db, [pro], cache),
fetchPortfolioCovers(db, pro.id),
]);
return success(c, { ...enrichedPro, portfolioCovers });
} catch (err) {
return handleError(c, err);
}
});
// Get pro's company profile (public data)
// NOTE: This route must be registered BEFORE /:id to avoid being shadowed by the catch-all
pros.get("/:id/company-profile", async (c) => {
try {
const services = c.get("services");
const proId = c.req.param("id");
// Verify pro exists and is published
const pro = await services.pro.getById(proId);
if (pro.status !== "published") {
return c.json({ error: "Pro not found" }, 404);
}
// Get the company profile
const profile = await services.companyProfile.getCompanyProfile(proId);
return success(c, profile);
} catch (err) {
return handleError(c, err);
}
});
// Get pro's published projects
// NOTE: This route must be registered BEFORE /:id to avoid being shadowed by the catch-all
pros.get("/:id/projects", async (c) => {
try {
const services = c.get("services");
const dal = c.get("dal");
const db = c.get("db");
const proId = c.req.param("id");
const { page, limit } = getPagination(
Number(c.req.query("page") || 1),
Number(c.req.query("limit") || 20),
);
// Verify pro exists and is published
const pro = await services.pro.getById(proId);
if (pro.status !== "published") {
return c.json({ error: "Pro not found" }, 404);
}
const filters = {
proId,
status: "published", // Only show published projects
};
const { projects: data, total } = await services.project.list(
filters,
page,
limit,
);
// Enrich with taxonomy data and resolve cover images via rooms/media cascade
const enrichedProjects = await enrichProjectsWithTaxonomy(
db,
services,
dal,
data,
);
return successWithPagination(
c,
enrichedProjects,
buildPaginationMeta(total, page, limit),
);
} catch (err) {
return handleError(c, err);
}
});
// Get full pro detail: pro + projects + company profile in one call
// NOTE: This route must be registered BEFORE /:id to avoid being shadowed by the catch-all
pros.get("/:id/full", async (c) => {
try {
const services = c.get("services");
const dal = c.get("dal");
const db = c.get("db");
const cache = c.get("cache");
const proId = c.req.param("id");
// Verify pro exists and is published (try ID first, then slug)
let pro = await services.pro.getById(proId).catch((err) => {
Eif (err instanceof NotFoundError) return null;
throw err;
});
if (!pro) {
pro = await services.pro.getBySlug(proId).catch((err) => {
Eif (err instanceof NotFoundError) return null;
throw err;
});
}
if (!pro || pro.status !== "published") {
return c.json({ success: false, error: { code: "NOT_FOUND", message: `Pro not found` } }, 404);
}
// Use the resolved pro.id for cache key and subsequent queries
const resolvedProId = pro.id;
const cacheKey = MARKETPLACE.proFull(resolvedProId);
const cached = await cache.get<{
pro: ProWithTaxonomy;
projects: unknown[];
companyProfile: unknown;
}>(cacheKey);
if (cached) {
return success(c, cached);
}
// Parallel fetch: enrich pro + projects + company profile + covers + total count
const [
enrichedPros,
projectsResult,
profileResult,
portfolioCovers,
projectCountRow,
] = await Promise.all([
enrichProsWithTaxonomy(db, [pro], cache),
services.project
.list({ proId: resolvedProId, status: "published" }, 1, 50)
.then(async ({ projects: data }) =>
enrichProjectsWithTaxonomy(db, services, dal, data),
),
services.companyProfile.getCompanyProfile(resolvedProId),
fetchPortfolioCovers(db, resolvedProId),
db
.select({ count: count() })
.from(projects)
.where(
and(
eq(projects.proId, resolvedProId),
eq(projects.status, "published"),
),
),
]);
const projectCount = projectCountRow[0]?.count ?? 0;
// Increment view count (fire and forget)
services.pro.incrementViewCount(pro.id).catch((err) => {
logger.error("Failed to increment view count:", err);
});
const result = {
pro: { ...enrichedPros[0], portfolioCovers, projectCount },
projects: projectsResult,
companyProfile: profileResult,
};
// Cache for 5 minutes (aligned with homepage TTL)
await cache.put(cacheKey, result, { l1Ttl: CACHE_TTL.MARKETPLACE_PRO_FULL_L1, l2Ttl: CACHE_TTL.MARKETPLACE_PRO_FULL_L2 });
return success(c, result);
} catch (err) {
return handleError(c, err);
}
});
// Get single published pro by ID
// NOTE: This catch-all route must be registered AFTER more specific routes like /:id/company-profile
pros.get("/:id", async (c) => {
try {
const services = c.get("services");
const db = c.get("db");
const cache = c.get("cache");
const paramId = c.req.param("id");
let pro = await services.pro.getById(paramId).catch((err) => {
if (err instanceof NotFoundError) return null;
throw err;
});
if (!pro) {
pro = await services.pro.getBySlug(paramId).catch((err) => {
Eif (err instanceof NotFoundError) return null;
throw err;
});
}
// Only return if pro is published
if (!pro || pro.status !== "published") {
return c.json({ success: false, error: { code: "NOT_FOUND", message: `Pro not found` } }, 404);
}
// Increment view count (fire and forget - don't block response)
services.pro.incrementViewCount(pro.id).catch((err) => {
logger.error("Failed to increment view count:", err);
});
// Enrich + attach portfolio covers in parallel.
const [[enrichedPro], portfolioCovers] = await Promise.all([
enrichProsWithTaxonomy(db, [pro], cache),
fetchPortfolioCovers(db, pro.id),
]);
return success(c, { ...enrichedPro, portfolioCovers });
} catch (err) {
return handleError(c, err);
}
});
/**
* Fetch all taxonomy tables, cached with 30-min KV TTL.
* On cache hit: 0 D1 queries. On miss: 5 parallel queries.
*/
async function getCachedTaxonomyTables(
db: ReturnType<typeof getDb>,
cache: DualCache,
): Promise<TaxonomyTables> {
return cache.getOrSet(
CACHE_KEYS.TAXONOMY_ENRICHMENT,
async () => {
// Fetch all 5 tables in parallel (instead of 3 sequential batches)
const [bt, cs, loc, z, ct] = await Promise.all([
db.select().from(businessTypes),
db.select().from(customerSegments),
db.select().from(localities),
db.select().from(zones),
db.select().from(cities),
]);
return {
businessTypes: bt,
customerSegments: cs,
localities: loc,
zones: z,
cities: ct,
};
},
{ l1Ttl: CACHE_TTL.TAXONOMY_L1, l2Ttl: CACHE_TTL.TAXONOMY_L2 },
);
}
// Helper function to enrich pros with taxonomy data
async function enrichProsWithTaxonomy(
db: ReturnType<typeof getDb>,
proList: Pro[],
cache: DualCache,
): Promise<ProWithTaxonomy[]> {
if (proList.length === 0) {
return [];
}
// Get all taxonomy tables from cache (0 queries on hit, 5 parallel on miss)
const taxonomy = await getCachedTaxonomyTables(db, cache);
// Create lookup maps from cached data
const businessTypesMap = new Map<string, BusinessType>();
for (const bt of taxonomy.businessTypes) {
businessTypesMap.set(bt.id, bt);
}
const customerSegmentsMap = new Map<string, CustomerSegment>();
for (const cs of taxonomy.customerSegments) {
customerSegmentsMap.set(cs.id, cs);
}
const localitiesMap = new Map<string, Locality>();
for (const loc of taxonomy.localities) {
localitiesMap.set(loc.id, loc);
}
const zonesMap = new Map<string, Zone>();
for (const zone of taxonomy.zones) {
zonesMap.set(zone.id, zone);
}
const citiesMap = new Map<string, City>();
for (const city of taxonomy.cities) {
citiesMap.set(city.id, city);
}
// Enrich pros with taxonomy data
const enrichedPros: ProWithTaxonomy[] = proList.map((pro) => {
const enriched: ProWithTaxonomy = { ...pro };
// Add business type name
if (pro.businessTypeId) {
const bt = businessTypesMap.get(pro.businessTypeId);
enriched.businessType = bt?.name || null;
}
// Add customer segment name
if (pro.customerSegmentId) {
const cs = customerSegmentsMap.get(pro.customerSegmentId);
enriched.customerSegment = cs?.name || null;
}
// Add locality with zone and city (first service area only)
if (pro.serviceAreaIds && pro.serviceAreaIds.length > 0) {
const localityId = pro.serviceAreaIds[0];
const locality = localitiesMap.get(localityId);
/* v8 ignore start -- defensive guard: locality always found in seeded data */
if (locality) {
/* v8 ignore stop */
const zone = zonesMap.get(locality.zoneId);
const city = zone ? citiesMap.get(zone.cityId) : undefined;
enriched.primaryLocality = {
id: locality.id,
name: locality.name,
zone: zone?.name || "",
city: city?.name || "",
};
}
}
return enriched;
});
return enrichedPros;
}
export default pros;
|