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 | 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 6x 6x 19x 19x 19x 19x 2x 17x 16x 16x 16x 16x 16x 19x 10x 19x 19x 2x 2x 4x 2x 19x 19x 16x 1x 1x 9x 9x 9x 9x 9x 9x 9x 3x 1x 8x 3x 3x 1x 2x 5x 5x 5x 1x 1x 4x 1x 4x 4x 4x 4x 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 9x 9x 9x 9x 9x 9x 9x 2x 9x 2x 1x 9x 2x 2x 2x 7x 7x 7x 7x 1x 6x 6x 5x 9x 9x 9x 5x 1x 1x 15x 15x 15x 15x 15x 15x 15x 3x 1x 14x 2x 1x 14x 3x 3x 3x 11x 11x 11x 1x 1x 10x 1x 10x 10x 10x 10x 1x | // Public Marketplace Pro Routes (API Key Protected)
import { and, count, eq, inArray } from "drizzle-orm";
import { Hono } from "hono";
import { projects } from "../../db/schema";
import {
CACHE_TTL,
MARKETPLACE,
MARKETPLACE_PROS_LIST_PREFIX,
getGeneration,
listCacheKey,
} from "../../lib/cache";
import { NotFoundError } from "../../lib/errors";
import { logger } from "../../lib/logger";
import {
handleError,
success,
successWithPagination,
} from "../../lib/response";
import { buildPaginationMeta, getPagination } from "../../lib/utils";
import type { ContextVariables } from "../../middleware";
import { resolveSlugRedirect } from "../../lib/slug-redirect";
import { enrichProjectsWithTaxonomy } from "./project-enrichment";
import {
enrichProsWithTaxonomy,
fetchPortfolioCovers,
type ProWithTaxonomy,
resolvePortfolioCoversForPros,
} from "./pros/taxonomy-enrichment";
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>();
// 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 = generation + filters + page + limit + fields. The
// generation counter (bumped on any pro/project/room write) makes every
// filter-combo key in the namespace stale in O(1) — a single counter
// bump replaces the old deletePattern sweep that could not enumerate the
// full filter space at 24h TTL. Orphaned keys idle out on their own TTL.
const gen = await getGeneration(cache, "pros");
const cacheKey = listCacheKey(
MARKETPLACE_PROS_LIST_PREFIX,
gen,
`${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);
// Resolve up to 4 most-recent portfolio covers per pro. Falls back through
// rooms→media for projects whose denormalized `projects.coverImage` is NULL,
// matching the cover cascade used by `enrichProjectsWithTaxonomy` on the
// detail page. Without this, pros whose project rows never had
// `coverImage` denormalized would show the "No portfolio yet" placeholder
// even though the detail page's Portfolio grid is populated from the
// same rooms→media chain.
const dal = c.get("dal");
const proIds = enrichedPros.map((p) => p.id);
const coversByProId = await resolvePortfolioCoversForPros(db, dal, proIds);
// 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. 24h L2 TTL is safe because every
// pro/project/room write bumps the generation counter, making the
// entire namespace stale in O(1). 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.LIST_L1,
l2Ttl: CACHE_TTL.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 dal = c.get("dal");
const db = c.get("db");
const cache = c.get("cache");
const slug = c.req.param("slug");
const pro = await services.pro.getBySlug(slug).catch((err) => {
if (err instanceof NotFoundError) return null;
throw err;
});
// Only return if pro is published
if (!pro || pro.status !== "published") {
// Before returning 404, check if this was a renamed slug
const redirect = await resolveSlugRedirect(dal, "pro", slug);
if (redirect) {
return success(c, { redirectTo: redirect });
}
return c.json({ error: "Pro not found" }, 404);
}
// Cache lookup keyed by resolved pro.id (slug-change-safe). Only
// cached successful published results — 404/redirect paths never
// reach here.
const proCardKey = MARKETPLACE.proCard(pro.id);
const cachedCard = await cache.get<Record<string, unknown>>(proCardKey);
if (cachedCard) {
// Increment view count even on cache hit (fire and forget).
services.pro.incrementViewCount(pro.id).catch((err) => {
logger.error("Failed to increment view count:", err);
});
return success(c, cachedCard);
}
// 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, dal, pro.id),
]);
const proCardResult = { ...enrichedPro, portfolioCovers };
await cache.put(proCardKey, proCardResult, {
l1Ttl: CACHE_TTL.DETAIL_L1,
l2Ttl: CACHE_TTL.DETAIL_L2,
});
return success(c, proCardResult);
} 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") {
// Before returning 404, check if this was a renamed slug
const redirect = await resolveSlugRedirect(dal, "pro", proId);
Iif (redirect) {
return success(c, { redirectTo: redirect });
}
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, dal, 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 24h. Safe at this TTL because every write that mutates
// a pro (profile.routes.ts PUT, admin/pros.routes.ts PUT/enable/
// disable/featured/early-adopter, company-profile/* mutations) calls
// invalidateEntity("pro", { id }) which point-deletes this key.
await cache.put(cacheKey, result, {
l1Ttl: CACHE_TTL.DETAIL_L1,
l2Ttl: CACHE_TTL.DETAIL_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 dal = c.get("dal");
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") {
// Before returning 404, check if this was a renamed slug
const redirect = await resolveSlugRedirect(dal, "pro", paramId);
Iif (redirect) {
return success(c, { redirectTo: redirect });
}
return c.json(
{
success: false,
error: { code: "NOT_FOUND", message: `Pro not found` },
},
404,
);
}
// Cache lookup keyed by resolved pro.id (slug-change-safe). Only
// cached for published results — 404/redirect paths never reach here.
const proCardKey = MARKETPLACE.proCard(pro.id);
const cachedCard = await cache.get<Record<string, unknown>>(proCardKey);
if (cachedCard) {
// Increment view count even on cache hit (fire and forget).
services.pro.incrementViewCount(pro.id).catch((err) => {
logger.error("Failed to increment view count:", err);
});
return success(c, cachedCard);
}
// 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, dal, pro.id),
]);
const proCardResult = { ...enrichedPro, portfolioCovers };
await cache.put(proCardKey, proCardResult, {
l1Ttl: CACHE_TTL.DETAIL_L1,
l2Ttl: CACHE_TTL.DETAIL_L2,
});
return success(c, proCardResult);
} catch (err) {
return handleError(c, err);
}
});
export default pros;
|