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

94.31% Statements 83/88
77.41% Branches 24/31
100% Functions 11/11
94.31% Lines 83/88

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                                  3x               3x           3x                             3x       3x 2x 2x 2x 2x 2x 2x         2x             2x                     3x 2x 2x 2x 2x     2x         2x 1x     1x         1x   1x         3x 1x 1x 1x 1x 1x             3x 2x 2x 2x   2x 2x 2x 2x   2x 1x   1x   1x         1x   1x         3x 2x 2x 2x 2x       2x             1x   1x 1x     1x                 3x 2x 2x 2x 2x       2x         1x   1x 1x     1x                 3x 2x 2x 2x 2x 2x 1x   1x         3x 2x 2x 2x 2x 2x   2x               1x   1x 1x     1x                  
// Admin Blog Image Routes — parallel to pro/blogs/images.routes.ts but for
// admin-authored blogs (no owning pro). Mounted under /api/admin/blogs, which
// already requires platform-admin auth, so there is no per-pro access check.
// Admin uploads/pexels key under `admin/blogs/<id>/...` (see service).
import { Hono } from "hono";
import { z } from "zod";
import type { Dal } from "../../../dal";
import { BadRequestError, ValidationError } from "../../../lib/errors";
import { validateUploadedFile } from "../../../lib/file-validation";
import {
	handleError,
	success,
	successWithPagination,
} from "../../../lib/response";
import { buildPaginationMeta } from "../../../lib/utils";
import type { Services } from "../../../services";
 
const pexelsImageSchema = z.object({
	pexelsId: z.union([z.string(), z.number()]).transform(String),
	url: z.string().url(),
	width: z.number().int().min(0).optional(),
	height: z.number().int().min(0).optional(),
	altText: z.string().max(300).optional(),
});
 
const mediaImageSchema = z.object({
	mediaId: z.union([z.string(), z.number()]).transform(Number),
	altText: z.string().max(300).optional(),
	caption: z.string().max(500).optional(),
});
 
const updateImageSchema = z.object({
	altText: z.string().max(300).optional(),
	caption: z.string().max(500).optional(),
});
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
	};
};
 
const adminImages = new Hono<Env>();
 
// All-pros gallery pool (rooms → media) for the admin image picker. Optional
// `proId` narrows to one pro; `q`/`search` filters by alt/caption/filename.
adminImages.get("/images/gallery", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.req.query("proId") || undefined;
		const search = c.req.query("q") || c.req.query("search") || undefined;
		const page = Math.max(1, Number.parseInt(c.req.query("page") || "1", 10));
		const perPage = Math.min(
			60,
			Math.max(1, Number.parseInt(c.req.query("per_page") || "24", 10)),
		);
 
		const { items, total } = await dal.media.searchForBlog({
			proId,
			search,
			limit: perPage,
			offset: (page - 1) * perPage,
		});
 
		return successWithPagination(
			c,
			items,
			buildPaginationMeta(total, page, perPage),
		);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Pexels search proxy (admin)
adminImages.get("/images/search/pexels", async (c) => {
	try {
		const services = c.get("services");
		const query = c.req.query("q") || "";
		const page = Number.parseInt(c.req.query("page") || "1", 10);
		// Clamp to Pexels' own per_page max (80) so a forged value can't burn
		// the shared Pexels rate limit with one oversized upstream request.
		const perPage = Math.min(
			80,
			Math.max(1, Number.parseInt(c.req.query("per_page") || "20", 10)),
		);
 
		if (!query) {
			throw new ValidationError("Search query is required");
		}
 
		const results = await services.blogImages.searchPexels(
			query,
			page,
			perPage,
		);
		return success(c, results);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// List a blog's gallery images
adminImages.get("/:id/images", async (c) => {
	try {
		const services = c.get("services");
		const blogId = c.req.param("id");
		const images = await services.blogImages.getBlogImages(blogId);
		return success(c, images);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Upload a blog image to R2 (admin key scheme)
adminImages.post("/:id/images/upload", async (c) => {
	try {
		const services = c.get("services");
		const blogId = c.req.param("id");
 
		const formData = await c.req.formData();
		const file = formData.get("file") as File | null;
		const altText = formData.get("altText") as string | null;
		const caption = formData.get("caption") as string | null;
 
		if (!file) {
			throw new ValidationError("No file provided");
		}
		validateUploadedFile(file);
 
		const image = await services.blogImages.uploadAdminBlogImage(blogId, {
			file,
			altText,
			caption: caption || undefined,
		});
		return success(c, image, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Add a Pexels image (re-hosted to R2 under the admin key)
adminImages.post("/:id/images/pexels", async (c) => {
	try {
		const services = c.get("services");
		const blogId = c.req.param("id");
		const { pexelsId, url, width, height, altText } = pexelsImageSchema.parse(
			await c.req.json(),
		);
 
		const image = await services.blogImages.addPexelsImage(blogId, {
			pexelsId,
			url,
			width: width || 0,
			height: height || 0,
			altText,
		});
		return success(c, image, 201);
	} catch (err) {
		Eif (err instanceof z.ZodError) {
			return handleError(
				c,
				new BadRequestError(
					`Validation failed: ${err.issues.map((e) => e.message).join(", ")}`,
				),
			);
		}
		return handleError(c, err);
	}
});
 
// Reference any pro's gallery media item into the blog gallery
adminImages.post("/:id/images/media", async (c) => {
	try {
		const services = c.get("services");
		const blogId = c.req.param("id");
		const { mediaId, altText, caption } = mediaImageSchema.parse(
			await c.req.json(),
		);
 
		const image = await services.blogImages.addMediaImage(blogId, {
			mediaId,
			altText,
			caption,
		});
		return success(c, image, 201);
	} catch (err) {
		Eif (err instanceof z.ZodError) {
			return handleError(
				c,
				new BadRequestError(
					`Validation failed: ${err.issues.map((e) => e.message).join(", ")}`,
				),
			);
		}
		return handleError(c, err);
	}
});
 
// Delete a blog image
adminImages.delete("/:id/images/:imageId", async (c) => {
	try {
		const services = c.get("services");
		const blogId = c.req.param("id");
		const imageId = Number.parseInt(c.req.param("imageId"), 10);
		await services.blogImages.deleteImageAdmin(imageId, blogId);
		return success(c, { message: "Image deleted successfully" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Update image metadata
adminImages.put("/:id/images/:imageId", async (c) => {
	try {
		const services = c.get("services");
		const blogId = c.req.param("id");
		const imageId = Number.parseInt(c.req.param("imageId"), 10);
		const { altText, caption } = updateImageSchema.parse(await c.req.json());
 
		const updated = await services.blogImages.updateImageAdmin(
			imageId,
			blogId,
			{
				altText,
				caption,
			},
		);
		return success(c, updated);
	} catch (err) {
		Eif (err instanceof z.ZodError) {
			return handleError(
				c,
				new BadRequestError(
					`Validation failed: ${err.issues.map((e) => e.message).join(", ")}`,
				),
			);
		}
		return handleError(c, err);
	}
});
 
export default adminImages;