All files / routes/admin/blogs categories.routes.ts

100% Statements 62/62
100% Branches 38/38
100% Functions 5/5
100% Lines 62/62

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                                                    3x     3x 8x 8x 8x 8x   8x           8x 8x   8x         7x           1x         3x 3x 3x 3x   2x 1x     1x   2x         3x 10x 10x 10x     10x 1x       9x 9x 1x     8x 1x       7x     10x 6x 1x         5x                 5x   5x         3x 6x 6x 6x 6x     6x 5x 1x       4x                     4x 2x 2x 1x           3x               3x   3x         3x 3x 3x 3x   2x 1x     1x   2x          
// Admin Blog Category Routes
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import type { Services } from "../../../services";
import {
	success,
	successWithPagination,
	handleError,
} from "../../../lib/response";
import {
	buildPaginationMeta,
	generateId,
	generateSlug,
} from "../../../lib/utils";
import { ValidationError, NotFoundError } from "../../../lib/errors";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
	};
};
 
const categories = new Hono<Env>();
 
// List all categories — mounted at /categories, so path is /all → /api/admin/blogs/categories/all
categories.get("/all", async (c) => {
	try {
		const dal = c.get("dal");
		const limitParam = Number(c.req.query("limit") || 100);
		const safeLimit = Math.min(500, Math.max(1, limitParam));
 
		const filters = {
			parentId:
				c.req.query("parentId") === "null" ? null : c.req.query("parentId"),
			search: c.req.query("search"),
		};
 
		const page = Math.max(1, Number(c.req.query("page") || 1));
		const offset = (page - 1) * safeLimit;
 
		const [data, total] = await Promise.all([
			dal.blogCategories.findAll(filters, offset, safeLimit),
			dal.blogCategories.count(filters),
		]);
 
		return successWithPagination(
			c,
			data,
			buildPaginationMeta(total, page, safeLimit),
		);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get single category
categories.get("/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const category = await dal.blogCategories.findById(c.req.param("id"));
 
		if (!category) {
			throw new NotFoundError("Category not found");
		}
 
		return success(c, category);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Create category
categories.post("/", async (c) => {
	try {
		const dal = c.get("dal");
		const body = await c.req.json();
 
		// Validate required fields
		if (!body.name) {
			throw new ValidationError("Missing required field: name");
		}
 
		// Sanitize category name: trim whitespace and strip HTML tags
		const sanitizedName = body.name.trim().replace(/<[^>]*>/g, "");
		if (!sanitizedName) {
			throw new ValidationError("Missing required field: name");
		}
 
		if (body.slug && !/^[a-z0-9-]+$/.test(body.slug)) {
			throw new ValidationError("Slug may only contain lowercase letters, numbers, and hyphens");
		}
 
		// Generate slug from sanitized name if not provided
		const slug = body.slug || generateSlug(sanitizedName);
 
		// Check if slug already exists
		const slugExists = await dal.blogCategories.slugExists(slug);
		if (slugExists) {
			throw new ValidationError(
				`Slug "${slug}" already exists. Please provide a unique slug.`,
			);
		}
 
		const category = await dal.blogCategories.create({
			id: generateId(),
			name: sanitizedName,
			slug,
			description: body.description || null,
			parentId: body.parentId || null,
			displayOrder: body.displayOrder ?? 0,
		});
 
		return success(c, category, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Update category
categories.put("/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const body = await c.req.json();
		const id = c.req.param("id");
 
		// Check if category exists
		const existing = await dal.blogCategories.findById(id);
		if (!existing) {
			throw new NotFoundError("Category not found");
		}
 
		// Sanitize category name if provided
		const sanitizedName = body.name
			? body.name.trim().replace(/<[^>]*>/g, "")
			: undefined;
 
		/* v8 ignore start -- defensive guard: slug format always valid in tests */
		if (body.slug && !/^[a-z0-9-]+$/.test(body.slug)) {
			throw new ValidationError("Slug may only contain lowercase letters, numbers, and hyphens");
		}
		/* v8 ignore stop */
 
		// If slug is being changed, check for uniqueness
		if (body.slug && body.slug !== existing.slug) {
			const slugExists = await dal.blogCategories.slugExists(body.slug, id);
			if (slugExists) {
				throw new ValidationError(
					`Slug "${body.slug}" already exists. Please provide a unique slug.`,
				);
			}
		}
 
		const updated = await dal.blogCategories.update(id, {
			name: sanitizedName,
			slug: body.slug,
			description: body.description,
			parentId: body.parentId,
			displayOrder: body.displayOrder,
		});
 
		return success(c, updated);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Delete category
categories.delete("/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const deleted = await dal.blogCategories.delete(c.req.param("id"));
 
		if (!deleted) {
			throw new NotFoundError("Category not found");
		}
 
		return success(c, { message: "Category deleted successfully" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default categories;