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 | 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 15x 14x 14x 14x 16x 5x 5x 5x 1x 5x 1x 5x 16x 16x 14x 1x 1x 13x 13x 13x 13x 13x 13x 13x 1x 12x 11x 3x 8x 8x 13x 13x 13x 8x 2x 8x 2x 8x 1x 1x 7x 4x 4x 7x 7x 2x 2x 2x 7x 7x 7x 7x 7x 5x 1x 6x 6x 6x 6x 6x 1x 5x 4x 4x 4x 1x 1x 6x 6x 6x 6x 6x 1x 5x 4x 4x 4x 1x | // Marketplace Blog Routes (Public API)
import { Hono } from "hono";
import { inArray } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import type { Dal } from "../../dal";
import type { Services } from "../../services";
import * as schema from "../../db/schema";
import {
CACHE_TTL,
MARKETPLACE,
MARKETPLACE_BLOGS_LIST_PREFIX,
getGeneration,
listCacheKey,
} from "../../lib/cache";
import type { DualCache } from "../../lib/cache";
import {
success,
successWithPagination,
handleError,
} from "../../lib/response";
import { buildPaginationMeta } from "../../lib/utils";
import { NotFoundError } from "../../lib/errors";
type Env = {
Bindings: CloudflareBindings;
Variables: {
dal: Dal;
services: Services;
db: DrizzleD1Database<typeof schema>;
cache: DualCache;
};
};
const blogs = new Hono<Env>();
// ============================================================================
// PUBLIC BLOGS
// ============================================================================
// List published blogs with filters and pagination
blogs.get("/", async (c) => {
try {
const dal = c.get("dal");
const cache = c.get("cache");
const limitParam = Number(c.req.query("limit") || 20);
const safeLimit = Math.min(100, Math.max(1, limitParam));
const page = Math.max(1, Number(c.req.query("page") || 1));
const offset = (page - 1) * safeLimit;
const filters = {
status: "published", // Only published blogs
blogType: c.req.query("blogType"),
categoryId: c.req.query("categoryId"),
categoryIds: c.req.query("categoryIds"), // comma-separated for multi-select
cityId: c.req.query("cityId"),
search: c.req.query("search"),
// Keep meta.total honest — the route used to filter blogs without a
// published author in-memory after the count was taken.
requirePublishedAuthor: true,
};
// Gen-namespaced list cache: bumping the "blogs" generation invalidates
// every filter-combo key in O(1) without enumerating the key space.
const gen = await getGeneration(cache, "blogs");
const cacheKey = listCacheKey(
MARKETPLACE_BLOGS_LIST_PREFIX,
gen,
`${JSON.stringify(filters)}:p${page}:l${safeLimit}`,
);
const cachedList = await cache.get<{
data: unknown[];
pagination: ReturnType<typeof buildPaginationMeta>;
}>(cacheKey);
if (cachedList) {
return successWithPagination(c, cachedList.data, cachedList.pagination);
}
const [data, total] = await Promise.all([
dal.blogs.findAll(filters, offset, safeLimit),
dal.blogs.count(filters),
]);
// Bulk fetch tags and pros for all blogs (N+1 optimization)
const blogIds = data.map((b) => b.id);
const [tagMap, prosMap] = await Promise.all([
dal.blogTags.findByBlogIds(blogIds),
dal.blogPros.findProsByBlogIds(blogIds, "approved", "published"),
]);
// Get attribution types so we can pick the author pro
const allBlogPros =
blogIds.length > 0
? await dal.blogPros.findByBlogIds(blogIds, "approved")
: new Map<string, Array<{ proId: string; attributionType: string }>>();
const blogsWithMetadata = data.map((blog) => {
const pros = prosMap.get(blog.id) || [];
const blogProEntries = allBlogPros.get(blog.id) || [];
// Skip blogs where the author pro is not published
// (pros list already filtered to published-only, so empty means no published pro)
const authorEntry = blogProEntries.find(
(bp) => bp.attributionType === "author",
);
const primaryPro = authorEntry
? pros.find((p) => p.id === authorEntry.proId) || pros[0]
: pros[0];
return {
id: blog.id,
slug: blog.slug,
title: blog.title,
metaDescription: blog.metaDescription,
featuredImageUrl: blog.featuredImageUrl,
featuredImageAlt: blog.featuredImageAlt,
blogType: blog.blogType,
primaryKeyword: blog.primaryKeyword,
categoryId: blog.categoryId,
cityId: blog.cityId,
readTimeMinutes: blog.readTimeMinutes,
publishedAt: blog.publishedAt,
tags: tagMap.get(blog.id) || [],
// Include primary pro as author
pro: primaryPro
? {
id: primaryPro.id,
businessName: primaryPro.businessName,
slug: primaryPro.slug,
localityName: null, // Simplified for listing - city name can be added later if needed
}
: null,
};
});
// The DAL now enforces "has published-author OR is editorial" at the
// WHERE level via requirePublishedAuthor, so count() and findAll()
// agree. No post-fetch filtering needed.
const pagination = buildPaginationMeta(total, page, safeLimit);
await cache.put(
cacheKey,
{ data: blogsWithMetadata, pagination },
{ l1Ttl: CACHE_TTL.LIST_L1, l2Ttl: CACHE_TTL.LIST_L2 },
);
return successWithPagination(c, blogsWithMetadata, pagination);
} catch (err) {
return handleError(c, err);
}
});
// Get single blog by slug (full content with pros and projects)
blogs.get("/:slug", async (c) => {
try {
const dal = c.get("dal");
const cache = c.get("cache");
const slug = c.req.param("slug");
// Check cache before hitting D1
const detailCacheKey = MARKETPLACE.blogBySlug(slug);
const cachedDetail = await cache.get<unknown>(detailCacheKey);
if (cachedDetail) {
return success(c, cachedDetail);
}
const blog = await dal.blogs.findBySlug(slug);
if (!blog || blog.status !== "published") {
throw new NotFoundError("Blog not found");
}
// Bulk fetch all related data for this blog
const [tagsMap, prosMap, projectsMap] = await Promise.all([
dal.blogTags.findByBlogIds([blog.id]),
dal.blogPros.findProsByBlogIds([blog.id], "approved", "published"), // Only approved + published pros
dal.blogProjects.findFullProjectsByBlogIds([blog.id]),
]);
const tags = tagsMap.get(blog.id) || [];
const proEntities = prosMap.get(blog.id) || [];
const projectData = projectsMap.get(blog.id) || [];
// Get attribution types from blog_pros table
const blogPros = await dal.blogPros.findAll({
blogId: blog.id,
approvalStatus: "approved",
});
const attributionMap = new Map(
blogPros.map((bv) => [bv.proId, bv.attributionType]),
);
// If blog has an author pro but they're not published, hide the blog
const authorBlogPro = blogPros.find(
(bp) => bp.attributionType === "author",
);
if (
authorBlogPro &&
!proEntities.some((p) => p.id === authorBlogPro.proId)
) {
throw new NotFoundError("Blog not found");
}
// Get city names for pros
const cityIds = proEntities
.map((v) => v.cityId)
.filter((id): id is string => id !== null);
let cityMap = new Map<string, string>();
if (cityIds.length > 0) {
const db = c.get("db");
const cities = await db
.select({
id: schema.cities.id,
name: schema.cities.name,
})
.from(schema.cities)
.where(inArray(schema.cities.id, cityIds));
cityMap = new Map(cities.map((city) => [city.id, city.name]));
}
const pros = proEntities.map((pro) => ({
proId: pro.id,
attributionType: attributionMap.get(pro.id) || "project_feature",
pro: {
id: pro.id,
businessName: pro.businessName,
slug: pro.slug,
localityName: pro.cityId ? cityMap.get(pro.cityId) || null : null,
},
}));
// Projects are already sorted by displayOrder from the DAL method
const projects = projectData.map(({ project, displayOrder }) => ({
projectId: project.id,
displayOrder,
project: {
id: project.id,
title: project.title,
slug: project.slug,
description: project.description,
},
}));
const responsePayload = {
id: blog.id,
slug: blog.slug,
title: blog.title,
metaDescription: blog.metaDescription,
content: blog.content,
featuredImageUrl: blog.featuredImageUrl,
featuredImageAlt: blog.featuredImageAlt,
blogType: blog.blogType,
primaryKeyword: blog.primaryKeyword,
secondaryKeywords: blog.secondaryKeywords,
categoryId: blog.categoryId,
cityId: blog.cityId,
readTimeMinutes: blog.readTimeMinutes,
publishedAt: blog.publishedAt,
dateUpdated: blog.dateUpdated,
tags,
pros,
projects,
};
// Cache only published, found results — never cache 404 or redirect paths.
await cache.put(detailCacheKey, responsePayload, {
l1Ttl: CACHE_TTL.DETAIL_L1,
l2Ttl: CACHE_TTL.DETAIL_L2,
});
return success(c, responsePayload);
} catch (err) {
return handleError(c, err);
}
});
// ============================================================================
// BLOG CATEGORIES
// ============================================================================
// List all active categories (for navigation/filtering)
blogs.get("/categories/all", async (c) => {
try {
const dal = c.get("dal");
const cache = c.get("cache");
// Near-static whole-table cache — invalidated whenever a category is mutated.
const cached = await cache.get<unknown>(MARKETPLACE.blogCategories);
if (cached) {
return success(c, cached);
}
// Get all categories (no pagination for public categories list)
const categories = await dal.blogCategories.findAll({}, 0, 500);
// Return simplified category data
const simplifiedCategories = categories.map((cat) => ({
id: cat.id,
name: cat.name,
slug: cat.slug,
description: cat.description,
parentId: cat.parentId,
displayOrder: cat.displayOrder,
}));
await cache.put(MARKETPLACE.blogCategories, simplifiedCategories, {
l1Ttl: CACHE_TTL.NEARLY_STATIC_L1,
l2Ttl: CACHE_TTL.NEARLY_STATIC_L2,
});
return success(c, simplifiedCategories);
} catch (err) {
return handleError(c, err);
}
});
// ============================================================================
// BLOG TAGS
// ============================================================================
// List popular/active tags (for filtering)
blogs.get("/tags/all", async (c) => {
try {
const dal = c.get("dal");
const cache = c.get("cache");
// Near-static whole-table cache — invalidated whenever a tag is mutated.
const cached = await cache.get<unknown>(MARKETPLACE.blogTags);
if (cached) {
return success(c, cached);
}
// Get all tags (no pagination for public tags list)
const tags = await dal.blogTags.findAll({}, 0, 500);
// Return simplified tag data
const simplifiedTags = tags.map((tag) => ({
id: tag.id,
name: tag.name,
slug: tag.slug,
}));
await cache.put(MARKETPLACE.blogTags, simplifiedTags, {
l1Ttl: CACHE_TTL.NEARLY_STATIC_L1,
l2Ttl: CACHE_TTL.NEARLY_STATIC_L2,
});
return success(c, simplifiedTags);
} catch (err) {
return handleError(c, err);
}
});
export default blogs;
|