All files / src/lib upload.ts

91.66% Statements 22/24
86.66% Branches 13/15
100% Functions 5/5
91.66% Lines 22/24

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                                                                          13x             7x   2x   1x   1x   1x   2x                             10x 3x   7x                 3x                         2x       2x     2x           2x 1x           1x         1x                       7x 7x   7x       7x    
import { request, uploadFile } from "./api/base";
 
export interface UploadContext {
	type:
		| "project-photo"
		| "blog-cover"
		| "blog-image"
		| "profile"
		| "certification"
		| "leadership"
		| "testimonial"
		| "logo"
		| "cover"
		| "room-media";
	id?: string; // projectId, blogId, roomId
}
 
export interface UploadResult {
	uploadId: string;
	storageKey: string;
	entityId?: string | number;
}
 
interface PresignedUrlResponse {
	uploadId: string;
	presignedUrl: string;
	storageKey: string;
}
 
interface ConfirmResponse {
	entityId?: string | number;
}
 
/**
 * Returns true when using worker-based uploads (local dev or when VITE_UPLOAD_MODE is unset).
 */
export function isWorkerMode(): boolean {
	return (import.meta.env.VITE_UPLOAD_MODE || "worker") === "worker";
}
 
/**
 * Map an UploadContext to the correct worker-mode API endpoint.
 */
function getWorkerEndpoint(proId: string, context: UploadContext): string {
	switch (context.type) {
		case "project-photo":
			return `/api/pro/${proId}/projects/${context.id}/upload-photo`;
		case "blog-cover":
			return `/api/pro/${proId}/blogs/my-blogs/${context.id}/upload-cover`;
		case "blog-image":
			return `/api/pro/${proId}/blogs/my-blogs/${context.id}/images/upload`;
		case "room-media":
			return `/api/pro/${proId}/rooms/${context.id}/upload-media`;
		default:
			return `/api/pro/${proId}/upload`;
	}
}
 
/**
 * Upload an image using either presigned URL flow or worker flow.
 *
 * - Presigned mode (VITE_UPLOAD_MODE === 'presigned'): request presigned URL -> PUT to R2 -> confirm
 * - Worker mode (default): multipart upload through the API worker
 */
export async function uploadImage(
	proId: string,
	file: File,
	context: UploadContext,
): Promise<UploadResult> {
	if (!isWorkerMode()) {
		return uploadViaPresignedUrl(proId, file, context);
	}
	return uploadViaWorker(proId, file, context);
}
 
async function uploadViaPresignedUrl(
	proId: string,
	file: File,
	context: UploadContext,
): Promise<UploadResult> {
	// 1. Request presigned URL
	const { data } = await request<PresignedUrlResponse>(
		`/api/pro/${proId}/uploads/request`,
		{
			method: "POST",
			body: {
				fileName: file.name,
				contentType: file.type,
				context: context.type,
				contextId: context.id,
			},
		},
	);
 
	Iif (!data) {
		throw new Error("Failed to obtain presigned URL");
	}
 
	const { uploadId, presignedUrl, storageKey } = data;
 
	// 2. Upload directly to R2
	const uploadResponse = await fetch(presignedUrl, {
		method: "PUT",
		body: file,
		headers: { "Content-Type": file.type },
	});
 
	if (!uploadResponse.ok) {
		throw new Error(
			`Direct upload failed with status ${uploadResponse.status}`,
		);
	}
 
	// 3. Confirm upload
	const confirmResult = await request<ConfirmResponse>(
		`/api/pro/${proId}/uploads/${uploadId}/confirm`,
		{ method: "POST" },
	);
 
	return {
		uploadId,
		storageKey,
		entityId: confirmResult.data?.entityId,
	};
}
 
async function uploadViaWorker(
	proId: string,
	file: File,
	context: UploadContext,
): Promise<UploadResult> {
	const endpoint = getWorkerEndpoint(proId, context);
	const result = await uploadFile<UploadResult>(endpoint, file);
 
	Iif (!result.data) {
		throw new Error("Worker upload returned no data");
	}
 
	return result.data;
}