All files / routes/admin uploads.routes.ts

100% Statements 22/22
100% Branches 4/4
100% Functions 2/2
100% Lines 22/22

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                                          1x     1x 1x             1x 4x 4x 4x 4x 4x     4x   3x 3x   3x 1x     2x     2x 4x     4x 2x               2x             2x           2x          
// Admin Upload Routes - Handle image uploads to R2
import { Hono } from "hono";
import type { Dal } from "../../dal";
import type { getDb } from "../../db";
import type { Services } from "../../services";
import { success, handleError } from "../../lib/response";
import { generateId, requireUser } from "../../lib/utils";
import { ValidationError } from "../../lib/errors";
import { validateUploadedFile } from "../../lib/file-validation";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		db: ReturnType<typeof getDb>;
	};
};
 
const uploads = new Hono<Env>();
 
// Upload project photo for any pro (legacy — project_photos table removed, returns 410)
uploads.post("/projects/:projectId/upload-photo", async (c) => {
	return c.json(
		{ error: "Legacy photo upload is no longer supported. Use the rooms/media upload endpoint." },
		410,
	);
});
 
// Upload pro profile image (admin only)
uploads.post("/pros/:proId/upload-profile", async (c) => {
	try {
		const proId = c.req.param("proId");
		const services = c.get("services");
		const user = requireUser(c.get("user"));
		const r2 = c.env.R2;
 
		// Verify pro exists
		await services.pro.getById(proId);
 
		const formData = await c.req.formData();
		const file = formData.get("file") as File | null;
 
		if (!file) {
			throw new ValidationError("No file provided");
		}
 
		validateUploadedFile(file);
 
		// Generate unique filename
		const ext = file.name.split(".").pop() || "jpg";
		const filename = `${proId}/profile/${generateId()}.${ext}`;
 
		// Upload to R2
		const arrayBuffer = await file.arrayBuffer();
		await r2.put(filename, arrayBuffer, {
			httpMetadata: {
				contentType: file.type,
			},
		});
 
		// Update pro profile image
		// Store just the R2 path - clients will prepend /api/images/ when constructing URLs
		const pro = await services.pro.update(
			proId,
			{ profileImage: filename },
			user.id,
			true,
		);
 
		return success(c, {
			path: filename,
			url: `/api/images/${filename}`,
			pro,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default uploads;