All files / routes/admin/blogs index.ts

99.28% Statements 138/139
96.07% Branches 98/102
100% Functions 13/13
99.27% Lines 136/137

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                                                                                  18x 18x 2x           2x             2x 14x 14x 14x 14x       14x 14x   14x 1x 1x   13x     14x                         14x 14x           13x   6x     13x 13x   3x 3x 2x       13x             13x           1x         2x 4x 4x 4x 4x   4x 1x     3x 3x   1x         2x 3x 3x 3x   2x 1x       1x           1x             2x         2x 21x 21x 21x 21x     19x 3x           16x 14x       15x     21x 15x 2x           13x 13x                                               11x 1x   2x       11x 1x 1x                       11x         1x 2x                 11x     11x 11x 11x             11x   10x         2x 21x 21x 21x 21x 21x     21x     21x 20x 2x       18x 4x       17x 2x                     15x                                         14x 3x     3x 2x 2x               14x 3x     3x 2x 1x                         14x 3x     3x 2x 2x 2x                   14x       14x 14x 14x   21x 21x             14x   7x         2x 4x 4x 4x     4x 4x 1x     3x   2x         2x 2x 2x             2x   2x           2x         2x           2x 2x 2x 2x      
// Admin Blog Routes - Main CRUD + barrel for sub-routers
import { checkBlogWordLimit } from "@interioring/utils/validation/blog";
import { eq } from "drizzle-orm";
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import * as schema from "../../../db/schema";
import type { DualCache } from "../../../lib/cache";
import { invalidateEntity } from "../../../lib/cache-invalidation";
import { NotFoundError, ValidationError } from "../../../lib/errors";
import { logger } from "../../../lib/logger";
import {
	handleError,
	success,
	successWithPagination,
} from "../../../lib/response";
import {
	buildPaginationMeta,
	generateId,
	generateSlug,
	requireUser,
} from "../../../lib/utils";
import type { Services } from "../../../services";
import categoriesRoutes from "./categories.routes";
import editorialRoutes from "./editorial.routes";
import imagesRoutes from "./images.routes";
import lifecycleRoutes from "./lifecycle.routes";
import suggestionsRoutes from "./suggestions.routes";
import tagsRoutes from "./tags.routes";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		cache: DualCache;
	};
};
 
function assertBlogWordLimit(content: string) {
	const result = checkBlogWordLimit(content);
	if (!result.withinLimit) {
		throw new ValidationError(
			result.message ?? "Blog content exceeds the word limit.",
		);
	}
}
 
const blogs = new Hono<Env>();
 
// ============================================================================
// BLOGS
// ============================================================================
 
// List all 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));
 
		// Support both page-based and offset-based pagination
		let page: number;
		const offsetParam = c.req.query("offset");
		const pageParam = c.req.query("page");
 
		if (offsetParam !== undefined) {
			const offset = Math.max(0, Number(offsetParam));
			page = Math.floor(offset / safeLimit) + 1;
		} else {
			page = Math.max(1, Number(pageParam || 1));
		}
 
		const filters = {
			status: c.req.query("status")
				? c.req.query("status")?.split(",")
				: undefined,
			blogType: c.req.query("blogType"),
			categoryId: c.req.query("categoryId"),
			cityId: c.req.query("cityId"),
			ideaSource: c.req.query("ideaSource"),
			ideaSourceProId: c.req.query("ideaSourceProId"),
			createdBy: c.req.query("createdBy"),
			search: c.req.query("search"),
		};
 
		const offset = (page - 1) * safeLimit;
		const [data, total] = await Promise.all([
			dal.blogs.findAll(filters, offset, safeLimit),
			dal.blogs.count(filters),
		]);
 
		// Resolve pro names for blogs with ideaSourceProId
		const proIds = [
			...new Set(
				data.map((b) => b.ideaSourceProId).filter((id): id is string => !!id),
			),
		];
		const proNameMap: Record<string, string> = {};
		if (proIds.length > 0) {
			// Single keyed lookup instead of one findById per pro id.
			const prosById = await dal.pros.findByIds(proIds);
			for (const [id, pro] of prosById) {
				proNameMap[id] = pro.businessName;
			}
		}
 
		const enriched = data.map((blog) => ({
			...blog,
			ideaSourceProName: blog.ideaSourceProId
				? proNameMap[blog.ideaSourceProId] || null
				: null,
		}));
 
		return successWithPagination(
			c,
			enriched,
			buildPaginationMeta(total, page, safeLimit),
		);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Check blog slug availability
blogs.get("/check-slug", async (c) => {
	try {
		const dal = c.get("dal");
		const slug = c.req.query("slug");
		const excludeId = c.req.query("excludeId");
 
		if (!slug) {
			throw new ValidationError("slug query parameter is required");
		}
 
		const exists = await dal.blogs.slugExists(slug, excludeId || undefined);
		return success(c, { available: !exists });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get single blog by ID
blogs.get("/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const blog = await dal.blogs.findById(c.req.param("id"));
 
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Also fetch related data
		const [tags, pros, projects] = await Promise.all([
			dal.blogTags.findByBlogId(blog.id),
			dal.blogPros.findAll({ blogId: blog.id }),
			dal.blogProjects.findByBlogId(blog.id),
		]);
 
		return success(c, {
			...blog,
			tags,
			pros,
			projects,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Create new blog
blogs.post("/", async (c) => {
	try {
		const dal = c.get("dal");
		const user = requireUser(c.get("user"));
		const body = await c.req.json();
 
		// Validate required fields (content is optional — drafts start empty)
		if (!body.title || !body.blogType || !body.ideaSource) {
			throw new ValidationError(
				"Missing required fields: title, blogType, ideaSource",
			);
		}
 
		// Validate word limit only when content provided
		if (body.content) {
			assertBlogWordLimit(body.content);
		}
 
		// Generate slug from title if not provided
		const slug = body.slug || generateSlug(body.title);
 
		// Check if slug already exists
		const slugExists = await dal.blogs.slugExists(slug);
		if (slugExists) {
			throw new ValidationError(
				`Slug "${slug}" already exists. Please provide a unique slug.`,
			);
		}
 
		// Create blog + relationships sequentially (D1 doesn't support transactions)
		const blogId = generateId();
		const [blog] = await dal.db
			.insert(schema.blogs)
			.values({
				id: blogId,
				slug,
				title: body.title,
				metaDescription: body.metaDescription || null,
				content: body.content ?? "",
				featuredImageUrl: body.featuredImageUrl || null,
				featuredImageAlt: body.featuredImageAlt || null,
				status: body.status || "draft",
				blogType: body.blogType,
				primaryKeyword: body.primaryKeyword || null,
				secondaryKeywords: body.secondaryKeywords || null,
				categoryId: body.categoryId || null,
				cityId: body.cityId || null,
				ideaSource: body.ideaSource,
				ideaSourceProId: body.ideaSourceProId || null,
				readTimeMinutes: body.readTimeMinutes || null,
				createdBy: user.id,
			})
			.returning();
 
		// Add tags — bulk insert (one DB roundtrip; statement-level atomic)
		if (body.tagIds && Array.isArray(body.tagIds) && body.tagIds.length > 0) {
			await dal.db
				.insert(schema.blogTagAssignments)
				.values(body.tagIds.map((tagId: string) => ({ blogId, tagId })));
		}
 
		// Add pros — bulk insert
		if (body.proIds && Array.isArray(body.proIds) && body.proIds.length > 0) {
			await dal.db.insert(schema.blogPros).values(
				body.proIds.map((proId: string) => ({
					id: generateId(),
					blogId,
					proId,
					attributionType: "project_feature" as const,
					approvalStatus: "pending" as const,
					approvalRequestedAt: new Date(),
				})),
			);
		}
 
		// Add projects — bulk insert
		if (
			body.projectIds &&
			Array.isArray(body.projectIds) &&
			body.projectIds.length > 0
		) {
			await dal.db.insert(schema.blogProjects).values(
				body.projectIds.map((projectId: string, index: number) => ({
					id: generateId(),
					blogId,
					projectId,
					displayOrder: index,
				})),
			);
		}
 
		logger.info(`[Blog Create] Created blog ${blog.id} with relationships`);
 
		// Invalidate blog list caches so the new entry is visible immediately.
		try {
			const cache = c.get("cache");
			c.executionCtx.waitUntil(
				invalidateEntity(cache, "blog", { slug: blog.slug }),
			);
		} catch {
			/* executionCtx unavailable in tests */
		}
 
		return success(c, blog, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Update blog
blogs.put("/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const user = c.get("user");
		const body = await c.req.json();
		const id = c.req.param("id");
 
		// Verify user is authenticated (consistency with create route)
		requireUser(user);
 
		// Check if blog exists
		const existing = await dal.blogs.findById(id);
		if (!existing) {
			throw new NotFoundError("Blog not found");
		}
 
		// Validate word limit
		if (body.content) {
			assertBlogWordLimit(body.content);
		}
 
		// If slug is being changed, check for uniqueness
		if (body.slug && body.slug !== existing.slug) {
			const slugExists = await dal.blogs.slugExists(body.slug, id);
			/* v8 ignore start -- defensive guard: slug collision unlikely in tests */
			if (slugExists) {
				throw new ValidationError(
					`Slug "${body.slug}" already exists. Please provide a unique slug.`,
				);
			}
			/* v8 ignore stop */
		}
 
		// Update blog (D1 doesn't support transactions — use sequential operations)
		const [blog] = await dal.db
			.update(schema.blogs)
			.set({
				slug: body.slug,
				title: body.title,
				metaDescription: body.metaDescription,
				content: body.content,
				featuredImageUrl: body.featuredImageUrl,
				featuredImageAlt: body.featuredImageAlt,
				status: body.status,
				blogType: body.blogType,
				primaryKeyword: body.primaryKeyword,
				secondaryKeywords: body.secondaryKeywords,
				categoryId: body.categoryId,
				cityId: body.cityId,
				readTimeMinutes: body.readTimeMinutes,
			})
			.where(eq(schema.blogs.id, id))
			.returning();
 
		// Replace tags if provided
		if (body.tagIds !== undefined) {
			await dal.db
				.delete(schema.blogTagAssignments)
				.where(eq(schema.blogTagAssignments.blogId, id));
			if (Array.isArray(body.tagIds)) {
				for (const tagId of body.tagIds) {
					await dal.db
						.insert(schema.blogTagAssignments)
						.values({ blogId: id, tagId });
				}
			}
		}
 
		// Replace pros if provided
		if (body.proIds !== undefined) {
			await dal.db
				.delete(schema.blogPros)
				.where(eq(schema.blogPros.blogId, id));
			if (Array.isArray(body.proIds)) {
				for (const proId of body.proIds) {
					await dal.db.insert(schema.blogPros).values({
						id: generateId(),
						blogId: id,
						proId,
						attributionType: "project_feature",
						approvalStatus: "pending",
						approvalRequestedAt: new Date(),
					});
				}
			}
		}
 
		// Replace projects if provided
		if (body.projectIds !== undefined) {
			await dal.db
				.delete(schema.blogProjects)
				.where(eq(schema.blogProjects.blogId, id));
			if (Array.isArray(body.projectIds)) {
				let displayOrder = 0;
				for (const projectId of body.projectIds) {
					await dal.db.insert(schema.blogProjects).values({
						id: generateId(),
						blogId: id,
						projectId,
						displayOrder: displayOrder++,
					});
				}
			}
		}
 
		logger.info(`[Blog Update] Updated blog ${id} with relationships`);
 
		// Invalidate detail + list caches. Pass oldSlug when the slug changed so
		// the previous slug key is also evicted (otherwise the old URL stays cached).
		try {
			const cache = c.get("cache");
			const newSlug = blog.slug ?? existing.slug;
			const oldSlug =
				body.slug && body.slug !== existing.slug ? existing.slug : undefined;
			c.executionCtx.waitUntil(
				invalidateEntity(cache, "blog", { slug: newSlug, oldSlug }),
			);
		} catch {
			/* executionCtx unavailable in tests */
		}
 
		return success(c, blog);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Delete blog
blogs.delete("/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const id = c.req.param("id");
 
		// Fetch slug before deletion so we can point-invalidate the detail cache.
		const existing = await dal.blogs.findById(id);
		if (!existing) {
			throw new NotFoundError("Blog not found");
		}
 
		const deleted = await dal.blogs.delete(id);
 
		Iif (!deleted) {
			throw new NotFoundError("Blog not found");
		}
 
		// Invalidate the detail cache and bump the list generation.
		try {
			const cache = c.get("cache");
			c.executionCtx.waitUntil(
				invalidateEntity(cache, "blog", { slug: existing.slug }),
			);
		} catch {
			/* executionCtx unavailable in tests */
		}
 
		return success(c, { message: "Blog deleted successfully" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Publish, unpublish, upload-cover, and pros/projects association mutations
// live in ./lifecycle.routes.ts. Mounted at "/" so URL paths are unchanged.
blogs.route("/", lifecycleRoutes);
 
// Blog image management for admin-authored blogs (gallery list, upload, pexels,
// media reference, all-pros gallery pool). Mounted at "/" → /:id/images/* and
// /images/* paths under /api/admin/blogs.
blogs.route("/", imagesRoutes);
 
// ============================================================================
// SUB-ROUTERS
// ============================================================================
 
blogs.route("/categories", categoriesRoutes);
blogs.route("/tags", tagsRoutes);
blogs.route("/suggestions", suggestionsRoutes);
blogs.route("/editorial", editorialRoutes);
 
export default blogs;