All files / services blog-images.service.ts

100% Statements 38/38
100% Branches 22/22
100% Functions 9/9
100% Lines 38/38

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                                                                                                      39x 39x             11x 11x 3x       8x 8x       8x   8x 3x                       9x     9x 9x   9x         9x     9x                             4x     4x   4x                                       1x                         5x 5x 1x     4x         4x 1x     3x             2x             4x 4x 1x       3x     1x                     5x 5x 1x       4x   2x      
// Service Layer for Blog Images
import type { Dal } from "../dal";
import { generateId } from "../lib/utils";
import { NotFoundError, ForbiddenError, ValidationError } from "../lib/errors";
 
export interface UploadBlogImageInput {
	file: File;
	altText?: string | null;
	caption?: string;
}
 
export interface AddPexelsImageInput {
	pexelsId: string;
	url: string;
	width: number;
	height: number;
	altText?: string | null;
	photographer?: string;
	photographerUrl?: string;
}
 
export interface AddProjectImageInput {
	projectPhotoId: number;
	altText?: string | null;
	caption?: string;
}
 
export interface PexelsPhoto {
	id: number;
	width: number;
	height: number;
	url: string;
	photographer: string;
	photographer_url: string;
	src: {
		original: string;
		large: string;
		medium: string;
		small: string;
	};
}
 
export interface PexelsSearchResult {
	photos: PexelsPhoto[];
	total_results: number;
	page: number;
	per_page: number;
}
 
export class BlogImagesService {
	constructor(
		private dal: Dal,
		private env: CloudflareBindings,
	) {}
 
	/**
	 * Verify that a pro has access to a blog
	 */
	async verifyBlogAccess(blogId: string, proId: string): Promise<void> {
		const blog = await this.dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Check if pro created blog OR is featured in blog
		const isCreator = blog.ideaSourceProId === proId;
		const blogPros = await this.dal.blogPros.findAll({
			blogId,
			proId,
		});
		const isFeatured = blogPros.length > 0;
 
		if (!isCreator && !isFeatured) {
			throw new ForbiddenError("You don't have access to this blog");
		}
	}
 
	/**
	 * Upload a blog image to R2
	 */
	async uploadBlogImage(
		blogId: string,
		proId: string,
		input: UploadBlogImageInput,
	) {
		const { file, altText, caption } = input;
 
		// Upload to R2
		const ext = file.name.split(".").pop() || "jpg";
		const storageKey = `${proId}/blogs/${blogId}/${generateId()}.${ext}`;
 
		await this.env.R2.put(storageKey, await file.arrayBuffer(), {
			httpMetadata: { contentType: file.type },
		});
 
		// Get next sort order
		const sortOrder = await this.dal.blogImages.getNextSortOrder(blogId);
 
		// Create DB record
		return this.dal.blogImages.create({
			blogId,
			sourceType: "upload",
			storageKey,
			altText: altText || "",
			caption,
			fileSize: file.size,
			sortOrder,
		});
	}
 
	/**
	 * Add a Pexels stock image to gallery
	 */
	async addPexelsImage(blogId: string, input: AddPexelsImageInput) {
		const { pexelsId, url, width, height, altText } = input;
 
		// Get next sort order
		const sortOrder = await this.dal.blogImages.getNextSortOrder(blogId);
 
		return this.dal.blogImages.create({
			blogId,
			sourceType: "pexels",
			sourceId: pexelsId,
			storageKey: url, // Store Pexels URL directly
			altText: altText || "",
			width,
			height,
			sortOrder,
		});
	}
 
	/**
	 * Copy a project photo to blog gallery (legacy — project_photos removed)
	 */
	async addProjectPhoto(
		_blogId: string,
		_proId: string,
		_input: AddProjectImageInput,
	) {
		throw new ValidationError(
			"Adding project photos to blogs is no longer supported via project_photos. Use media (rooms) instead.",
		);
	}
 
	/**
	 * Search Pexels API
	 */
	async searchPexels(
		query: string,
		page = 1,
		perPage = 20,
	): Promise<PexelsSearchResult> {
		const apiKey = this.env.PEXELS_API_KEY;
		if (!apiKey) {
			throw new Error("Pexels API key not configured");
		}
 
		const response = await fetch(
			`https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}`,
			{ headers: { Authorization: apiKey } },
		);
 
		if (!response.ok) {
			throw new Error(`Pexels API error: ${response.statusText}`);
		}
 
		return response.json();
	}
 
	/**
	 * Get all images for a blog
	 */
	async getBlogImages(blogId: string) {
		return this.dal.blogImages.findByBlogId(blogId);
	}
 
	/**
	 * Delete an image
	 */
	async deleteImage(imageId: number, proId: string) {
		const image = await this.dal.blogImages.findById(imageId);
		if (!image) {
			throw new NotFoundError("Image not found");
		}
 
		// Verify pro has access to the blog
		await this.verifyBlogAccess(image.blogId, proId);
 
		// Delete from DB (R2 cleanup can be done separately)
		await this.dal.blogImages.delete(imageId);
	}
 
	/**
	 * Update image metadata
	 */
	async updateImage(
		imageId: number,
		proId: string,
		data: { altText?: string; caption?: string },
	) {
		const image = await this.dal.blogImages.findById(imageId);
		if (!image) {
			throw new NotFoundError("Image not found");
		}
 
		// Verify pro has access to the blog
		await this.verifyBlogAccess(image.blogId, proId);
 
		return this.dal.blogImages.update(imageId, data);
	}
}