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

98.43% Statements 126/128
95.83% Branches 46/48
90.9% Functions 10/11
99.2% Lines 124/125

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                      1x               1x           1x                                 1x     1x     1x 11x 11x 11x 11x   11x 1x     10x   10x 10x 1x       9x       1x     8x 8x 8x   8x 1x     7x     7x 7x 11x     11x 5x             5x 5x         5x                 6x         1x 4x 4x 4x 4x 4x   4x 1x       3x     2x   2x   2x         1x 6x 6x 6x 6x   6x 1x       5x     4x 4x 4x 4x   4x 1x         3x     3x           3x   3x         1x 7x 7x 7x 7x   7x 1x       6x   5x     5x               3x   4x 2x   2x         1x 5x 5x 5x 5x   5x 1x       4x   3x     3x           2x   3x 1x   2x         1x 4x 4x 4x 4x 4x   4x 1x     3x           2x   2x         1x 4x 4x 4x 4x   4x 1x     3x   1x   3x         1x 5x 5x 5x 5x   5x 1x     4x   4x         1x   4x     4x          
// Pro Blog Image Routes
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import type { Services } from "../../../services";
import { success, handleError } from "../../../lib/response";
import { z } from "zod";
import { ValidationError, NotFoundError, ForbiddenError, BadRequestError } from "../../../lib/errors";
import { validateUploadedFile } from "../../../lib/file-validation";
import { generateId } from "../../../lib/utils";
import { requireProManager } from "../../../middleware";
 
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 projectPhotoSchema = z.object({
	projectPhotoId: 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;
		proId: string;
		proRole: string;
	};
};
 
const images = new Hono<Env>();
 
// Apply pro access middleware to all routes
images.use("*", requireProManager);
 
// Upload blog cover image
images.post("/my-blogs/:id/upload-cover", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
		const r2 = c.env.R2;
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		const blogId = c.req.param("id");
 
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Verify pro owns this blog
		if (
			blog.ideaSourceProId !== proId ||
			blog.ideaSource !== "pro_request"
		) {
			throw new ForbiddenError("You do not have access to this blog");
		}
 
		const formData = await c.req.formData();
		const file = formData.get("file") as File | null;
		const altText = formData.get("altText") as string | null;
 
		if (!file) {
			throw new ValidationError("No file provided");
		}
 
		validateUploadedFile(file);
 
		// Generate unique filename per upload to bust CDN/browser cache
		const mimeToExt: Record<string, string> = { "image/jpeg": "jpg", "image/png": "png", "image/webp": "webp", "image/gif": "gif", "image/avif": "avif" };
		const ext = mimeToExt[file.type] || "jpg";
		const filename = `${proId}/blogs/${blogId}/cover-${generateId()}.${ext}`;
 
		// Upload to R2
		const arrayBuffer = await file.arrayBuffer();
		await r2.put(filename, arrayBuffer, {
			httpMetadata: {
				contentType: file.type,
			},
		});
 
		// Update blog record with cover image URL
		const imageUrl = `/api/images/${filename}`;
		const updated = await dal.blogs.update(blogId, {
			featuredImageUrl: imageUrl,
			featuredImageAlt: altText || null,
		});
 
		return success(
			c,
			{
				blog: updated,
				imageUrl,
			},
			200,
		);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get all images for a blog
images.get("/my-blogs/:id/images", async (c) => {
	try {
		const dal = c.get("dal");
		const services = c.get("services");
		const proId = c.get("proId");
		const blogId = c.req.param("id");
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		// Verify access
		await services.blogImages.verifyBlogAccess(blogId, proId);
 
		// Get images
		const blogImages = await dal.blogImages.findByBlogId(blogId);
 
		return success(c, blogImages);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Upload blog image
images.post("/my-blogs/:id/images/upload", async (c) => {
	try {
		const services = c.get("services");
		const proId = c.get("proId");
		const blogId = c.req.param("id");
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		// Verify access
		await services.blogImages.verifyBlogAccess(blogId, proId);
 
		// Get form data
		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");
		}
 
		// Alt text is optional — users can add it later
 
		validateUploadedFile(file);
 
		// Upload image
		const image = await services.blogImages.uploadBlogImage(blogId, proId, {
			file,
			altText,
			caption: caption || undefined,
		});
 
		return success(c, image, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Add Pexels image to gallery
images.post("/my-blogs/:id/images/pexels", async (c) => {
	try {
		const services = c.get("services");
		const proId = c.get("proId");
		const blogId = c.req.param("id");
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		// Verify access
		await services.blogImages.verifyBlogAccess(blogId, proId);
 
		const { pexelsId, url, width, height, altText } = pexelsImageSchema.parse(await c.req.json());
 
		// Add Pexels image
		const image = await services.blogImages.addPexelsImage(blogId, {
			pexelsId,
			url,
			width: width || 0,
			height: height || 0,
			altText,
		});
 
		return success(c, image, 201);
	} catch (err) {
		if (err instanceof z.ZodError) {
			return handleError(c, new BadRequestError(`Validation failed: ${err.issues.map((e) => e.message).join(", ")}`));
		}
		return handleError(c, err);
	}
});
 
// Add project photo to gallery
images.post("/my-blogs/:id/images/project", async (c) => {
	try {
		const services = c.get("services");
		const proId = c.get("proId");
		const blogId = c.req.param("id");
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		// Verify access
		await services.blogImages.verifyBlogAccess(blogId, proId);
 
		const { projectPhotoId, altText, caption } = projectPhotoSchema.parse(await c.req.json());
 
		// Add project photo
		const image = await services.blogImages.addProjectPhoto(blogId, proId, {
			projectPhotoId,
			altText,
			caption,
		});
 
		return success(c, image, 201);
	} catch (err) {
		if (err instanceof z.ZodError) {
			return handleError(c, new BadRequestError(`Validation failed: ${err.issues.map((e) => e.message).join(", ")}`));
		}
		return handleError(c, err);
	}
});
 
// Search Pexels (proxied)
images.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);
		const perPage = 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);
	}
});
 
// Delete blog image
images.delete("/my-blogs/:blogId/images/:imageId", async (c) => {
	try {
		const services = c.get("services");
		const proId = c.get("proId");
		const imageId = Number.parseInt(c.req.param("imageId"), 10);
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		await services.blogImages.deleteImage(imageId, proId);
 
		return success(c, { message: "Image deleted successfully" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Update image metadata
images.put("/my-blogs/:blogId/images/:imageId", async (c) => {
	try {
		const services = c.get("services");
		const proId = c.get("proId");
		const imageId = Number.parseInt(c.req.param("imageId"), 10);
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		const { altText, caption } = updateImageSchema.parse(await c.req.json());
 
		const updated = await services.blogImages.updateImage(imageId, proId, {
			altText,
			caption,
		});
 
		return success(c, updated);
	} catch (err) {
		Iif (err instanceof z.ZodError) {
			return handleError(c, new BadRequestError(`Validation failed: ${err.issues.map((e) => e.message).join(", ")}`));
		}
		return handleError(c, err);
	}
});
 
export default images;