All files / routes/pro/blogs features.routes.ts

100% Statements 21/21
100% Branches 6/6
100% Functions 3/3
100% Lines 19/19

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                                                1x     1x     1x 13x 13x 13x   13x 1x     12x 13x   13x 13x   13x         13x           11x 11x   10x         10x           3x          
// Pro Blog Features Routes (blogs featuring this pro)
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import type { Services } from "../../../services";
import {
	successWithPagination,
	handleError,
} from "../../../lib/response";
import { buildPaginationMeta } from "../../../lib/utils";
import { ForbiddenError } from "../../../lib/errors";
import { requireProAccess } from "../../../middleware";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		proId: string;
		proRole: string;
	};
};
 
const features = new Hono<Env>();
 
// Apply pro access middleware to all routes
features.use("*", requireProAccess);
 
// Get blogs featuring this pro
features.get("/", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		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 = {
			proId,
			approvalStatus: c.req.query("status")?.split(","),
		};
 
		const [blogPros, total] = await Promise.all([
			dal.blogPros.findAll(filters, offset, safeLimit),
			dal.blogPros.count(filters),
		]);
 
		// Bulk fetch the associated blogs (N+1 optimization)
		const blogIds = blogPros.map((bv) => bv.blogId);
		const blogMap = await dal.blogs.findByIds(blogIds);
 
		const results = blogPros.map((bv) => ({
			...bv,
			blog: blogMap.get(bv.blogId),
		}));
 
		return successWithPagination(
			c,
			results,
			buildPaginationMeta(total, page, safeLimit),
		);
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default features;