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 | 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 13x 13x 13x 14x 5x 5x 5x 5x 1x 5x 14x 1x 1x 11x 11x 11x 11x 10x 3x 7x 7x 11x 11x 11x 7x 2x 7x 7x 1x 6x 4x 4x 6x 6x 2x 2x 2x 6x 6x 6x 5x 1x 4x 4x 4x 3x 3x 1x 1x 4x 4x 4x 3x 3x 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 {
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>;
};
};
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 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,
};
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.
return successWithPagination(
c,
blogsWithMetadata,
buildPaginationMeta(total, page, safeLimit),
);
} 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 slug = c.req.param("slug");
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,
},
}));
return success(c, {
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,
});
} 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");
// 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,
}));
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");
// 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,
}));
return success(c, simplifiedTags);
} catch (err) {
return handleError(c, err);
}
});
export default blogs;
|