All files / dal blog-images.dal.ts

100% Statements 16/16
100% Branches 4/4
100% Functions 9/9
100% Lines 15/15

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              78x     2x               2x         2x       1x       1x             3x         3x       2x           2x 1x 3x                   1x           3x       3x      
// Data Access Layer for Blog Images
import { and, asc, eq, sql } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import type { BlogImage, NewBlogImage } from "../db/schema/index.js";
import * as schema 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> {
		// D1 has no BEGIN/COMMIT (db.transaction() throws at runtime); batch()
		// is the atomic unit.
		if (imageIds.length === 0) return;
		const updates = imageIds.map((imageId, i) =>
			this.db
				.update(schema.blogImages)
				.set({ sortOrder: i, dateUpdated: new Date() })
				.where(
					and(
						eq(schema.blogImages.id, imageId),
						eq(schema.blogImages.blogId, blogId),
					),
				),
		);
		await this.db.batch(
			updates as [(typeof updates)[number], ...typeof updates],
		);
	}
 
	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;
	}
}