All files / src/lib/api blog-images.ts

100% Statements 24/24
78.94% Branches 30/38
100% Functions 11/11
100% Lines 23/23

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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382                                                                                                                                                                                                                                                        93x                     1x                                 2x                                           1x                                                         1x                                                     2x           2x                                 1x                                           1x                                   2x 2x       2x 2x     2x                                         2x                                           5x                             7x 2x     5x 1x           4x 1x           3x      
// Blog Images API Client
import {
	request,
	uploadFile,
	getImageUrl as resolveImageUrl,
	type ApiResponse,
} from "./base";
 
// ============================================================================
// TYPES
// ============================================================================
 
export type BlogImageSourceType = "upload" | "pexels" | "project" | "media";
 
export type BlogImage = {
	id: number;
	blogId: string;
	sourceType: BlogImageSourceType;
	sourceId: string | null;
	storageKey: string; // R2 key or Pexels URL
	thumbnailKey: string | null;
	altText: string; // Required for SEO
	caption: string | null;
	width: number | null;
	height: number | null;
	fileSize: number | null;
	sortOrder: number;
	isUsedInContent: boolean;
	dateCreated: number;
	dateUpdated: number;
};
 
export type PexelsPhoto = {
	id: number;
	width: number;
	height: number;
	url: string;
	photographer: string;
	photographer_url: string;
	photographer_id: number;
	avg_color: string;
	src: {
		original: string;
		large2x: string;
		large: string;
		medium: string;
		small: string;
		portrait: string;
		landscape: string;
		tiny: string;
	};
	liked: boolean;
	alt: string;
};
 
export type PexelsSearchResult = {
	page: number;
	per_page: number;
	photos: PexelsPhoto[];
	total_results: number;
	next_page?: string;
	prev_page?: string;
};
 
export type UploadBlogImageInput = {
	file: File;
	altText: string;
	caption?: string;
};
 
export type AddPexelsImageInput = {
	pexelsId: string;
	url: string;
	width: number;
	height: number;
	altText: string;
	photographer?: string;
	photographerUrl?: string;
};
 
export type AddProjectImageInput = {
	projectPhotoId: number;
	altText: string;
	caption?: string;
};
 
export type UpdateBlogImageInput = {
	altText?: string;
	caption?: string;
};
 
/** A row returned by the pro media-search endpoint. */
export type BlogMediaItem = {
	id: number;
	storageKey: string;
	altText: string | null;
	caption: string | null;
	width: number | null;
	height: number | null;
	proId: string;
};
 
export type BlogMediaPage = {
	data: BlogMediaItem[];
	meta: {
		total: number;
		page: number;
		limit: number;
		totalPages: number;
		hasNext: boolean;
		hasPrev: boolean;
	};
};
 
export type AddMediaImageInput = {
	mediaId: number;
	altText?: string;
	caption?: string;
};
 
// ============================================================================
// API CLIENT
// ============================================================================
 
export const blogImagesApi = {
	/**
	 * Get all images for a blog
	 * @param proId - Pro ID
	 * @param blogId - Blog ID
	 * @returns Array of blog images sorted by sortOrder
	 */
	async getBlogImages(
		proId: string,
		blogId: string,
	): Promise<ApiResponse<BlogImage[]>> {
		return request<BlogImage[]>(
			`/api/pro/${proId}/blogs/my-blogs/${blogId}/images`,
		);
	},
 
	/**
	 * Upload a new image to R2
	 * @param proId - Pro ID
	 * @param blogId - Blog ID
	 * @param input - Upload input (file, altText, optional caption)
	 * @returns Uploaded blog image record
	 */
	async uploadBlogImage(
		proId: string,
		blogId: string,
		input: UploadBlogImageInput,
	): Promise<ApiResponse<BlogImage>> {
		return uploadFile<BlogImage>(
			`/api/pro/${proId}/blogs/my-blogs/${blogId}/images/upload`,
			input.file,
			{
				altText: input.altText,
				...(input.caption && { caption: input.caption }),
			},
		);
	},
 
	/**
	 * Add a Pexels stock photo to the gallery
	 * @param proId - Pro ID
	 * @param blogId - Blog ID
	 * @param input - Pexels image data
	 * @returns Blog image record
	 */
	async addPexelsImage(
		proId: string,
		blogId: string,
		input: AddPexelsImageInput,
	): Promise<ApiResponse<BlogImage>> {
		return request<BlogImage>(
			`/api/pro/${proId}/blogs/my-blogs/${blogId}/images/pexels`,
			{
				method: "POST",
				body: {
					pexelsId: input.pexelsId,
					url: input.url,
					width: input.width,
					height: input.height,
					altText: input.altText,
					photographer: input.photographer,
					photographerUrl: input.photographerUrl,
				},
			},
		);
	},
 
	/**
	 * Copy a project photo to the blog gallery
	 * @param proId - Pro ID
	 * @param blogId - Blog ID
	 * @param input - Project photo data
	 * @returns Blog image record
	 */
	async addProjectImage(
		proId: string,
		blogId: string,
		input: AddProjectImageInput,
	): Promise<ApiResponse<BlogImage>> {
		return request<BlogImage>(
			`/api/pro/${proId}/blogs/my-blogs/${blogId}/images/project`,
			{
				method: "POST",
				body: {
					projectPhotoId: input.projectPhotoId,
					altText: input.altText,
					caption: input.caption,
				},
			},
		);
	},
 
	/**
	 * Search Pexels for stock photos
	 * @param proId - Pro ID (for auth)
	 * @param query - Search query
	 * @param page - Page number (default: 1)
	 * @param perPage - Results per page (default: 20, max: 80)
	 * @returns Pexels search results
	 */
	async searchPexels(
		proId: string,
		query: string,
		page = 1,
		perPage = 20,
	): Promise<ApiResponse<PexelsSearchResult>> {
		const params = new URLSearchParams({
			q: query,
			page: page.toString(),
			per_page: perPage.toString(),
		});
 
		return request<PexelsSearchResult>(
			`/api/pro/${proId}/blogs/images/search/pexels?${params.toString()}`,
		);
	},
 
	/**
	 * Delete an image from the gallery
	 * @param proId - Pro ID
	 * @param blogId - Blog ID
	 * @param imageId - Image ID to delete
	 * @returns Success response
	 */
	async deleteImage(
		proId: string,
		blogId: string,
		imageId: number,
	): Promise<ApiResponse<{ message: string }>> {
		return request<{ message: string }>(
			`/api/pro/${proId}/blogs/my-blogs/${blogId}/images/${imageId}`,
			{
				method: "DELETE",
			},
		);
	},
 
	/**
	 * Update image metadata (alt text, caption)
	 * @param proId - Pro ID
	 * @param blogId - Blog ID
	 * @param imageId - Image ID to update
	 * @param input - Updated fields
	 * @returns Updated blog image record
	 */
	async updateImage(
		proId: string,
		blogId: string,
		imageId: number,
		input: UpdateBlogImageInput,
	): Promise<ApiResponse<BlogImage>> {
		return request<BlogImage>(
			`/api/pro/${proId}/blogs/my-blogs/${blogId}/images/${imageId}`,
			{
				method: "PUT",
				body: input,
			},
		);
	},
 
	/**
	 * Search the pro's media library for images to insert into a blog.
	 * Query is optional — an empty query returns all media for the pro.
	 */
	async searchProMedia(
		proId: string,
		blogId: string,
		params: { search?: string; page?: number; perPage?: number } = {},
	): Promise<BlogMediaPage> {
		const { search = "", page = 1, perPage = 20 } = params;
		const qs = new URLSearchParams({
			page: page.toString(),
			per_page: perPage.toString(),
		});
		if (search.trim()) qs.set("q", search.trim());
		const response = await request<BlogMediaItem[]>(
			`/api/pro/${proId}/blogs/my-blogs/${blogId}/media?${qs.toString()}`,
		);
		return {
			data: response.data ?? [],
			meta: {
				total: response.meta?.total ?? 0,
				page: response.meta?.page ?? page,
				limit: response.meta?.limit ?? perPage,
				totalPages: response.meta?.totalPages ?? 1,
				hasNext: response.meta?.hasNext ?? false,
				hasPrev: response.meta?.hasPrev ?? false,
			},
		};
	},
 
	/**
	 * Link a media library item to the blog's image gallery.
	 */
	async addMediaImage(
		proId: string,
		blogId: string,
		input: AddMediaImageInput,
	): Promise<ApiResponse<BlogImage>> {
		return request<BlogImage>(
			`/api/pro/${proId}/blogs/my-blogs/${blogId}/images/media`,
			{
				method: "POST",
				body: {
					mediaId: input.mediaId,
					...(input.altText !== undefined && { altText: input.altText }),
					...(input.caption !== undefined && { caption: input.caption }),
				},
			},
		);
	},
 
	/**
	 * Helper: Get image URL for display.
	 * storageKey is an R2 key for upload/media/re-hosted-pexels images (→ prepend
	 * the API base via /api/images), but legacy pexels rows stored an external
	 * URL directly. Branch on the scheme so both keep working.
	 * @param image - Blog image record
	 * @returns Full image URL
	 */
	getImageUrl(image: BlogImage): string {
		return image.storageKey.startsWith("http")
			? image.storageKey
			: resolveImageUrl(image.storageKey);
	},
 
	/**
	 * Helper: Validate alt text
	 * @param altText - Alt text to validate
	 * @returns Validation result
	 */
	validateAltText(altText: string): {
		valid: boolean;
		error?: string;
	} {
		// Empty alt text is allowed — users can add it later
		if (!altText || altText.trim().length === 0) {
			return { valid: true };
		}
 
		if (altText.length < 10) {
			return {
				valid: false,
				error: "Alt text must be at least 10 characters for SEO",
			};
		}
 
		if (altText.length > 125) {
			return {
				valid: false,
				error: "Alt text must be less than 125 characters",
			};
		}
 
		return { valid: true };
	},
};