All files / dal blog-images.dal.ts

100% Statements 15/15
100% Branches 2/2
100% Functions 9/9
100% Lines 14/14

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              29x     2x               2x         2x       1x       1x             3x         3x       2x       2x 2x 3x                           3x       3x      
// Data Access Layer for Blog Images
import { eq, and, sql, asc } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema/index.js";
import type { BlogImage, NewBlogImage } from "../db/schema/index.js";
 
export class BlogImagesDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	async findByBlogId(blogId: string): Promise<BlogImage[]> {
		return this.db
			.select()
			.from(schema.blogImages)
			.where(eq(schema.blogImages.blogId, blogId))
			.orderBy(asc(schema.blogImages.sortOrder));
	}
 
	async findById(id: number): Promise<BlogImage | undefined> {
		const result = await this.db
			.select()
			.from(schema.blogImages)
			.where(eq(schema.blogImages.id, id))
			.limit(1);
		return result[0];
	}
 
	async create(data: NewBlogImage): Promise<BlogImage> {
		const result = await this.db
			.insert(schema.blogImages)
			.values(data)
			.returning();
		return result[0];
	}
 
	async update(
		id: number,
		data: Partial<Omit<BlogImage, "id" | "dateCreated">>,
	): Promise<BlogImage | undefined> {
		const result = await this.db
			.update(schema.blogImages)
			.set({ ...data, dateUpdated: new Date() })
			.where(eq(schema.blogImages.id, id))
			.returning();
		return result[0];
	}
 
	async delete(id: number): Promise<void> {
		await this.db.delete(schema.blogImages).where(eq(schema.blogImages.id, id));
	}
 
	async reorder(blogId: string, imageIds: number[]): Promise<void> {
		await this.db.transaction(async (tx) => {
			for (let i = 0; i < imageIds.length; i++) {
				await tx
					.update(schema.blogImages)
					.set({ sortOrder: i, dateUpdated: new Date() })
					.where(
						and(
							eq(schema.blogImages.id, imageIds[i]),
							eq(schema.blogImages.blogId, blogId),
						),
					);
			}
		});
	}
 
	async getNextSortOrder(blogId: string): Promise<number> {
		const result = await this.db
			.select({ maxSort: sql<number>`COALESCE(MAX(sort_order), -1)` })
			.from(schema.blogImages)
			.where(eq(schema.blogImages.blogId, blogId));
		return (result[0]?.maxSort ?? -1) + 1;
	}
}