All files / dal blog-tags.dal.ts

100% Statements 47/47
100% Branches 22/22
100% Functions 14/14
100% Lines 45/45

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                        69x                     5x   5x 1x 1x     5x             5x 1x     4x       4x   4x 1x 1x     4x         4x       3x       2x         2x       2x         2x       1x       1x             2x         2x       2x       2x       5x 5x 1x   5x       5x               2x                         2x                 5x   3x                             3x 3x 6x 6x       6x               3x       1x       2x                 2x       1x          
// Data Access Layer for Blog Tags and Tag Assignments
import { eq, like, sql, and, inArray } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type { BlogTag, NewBlogTag, NewBlogTagAssignment } from "../db/schema";
import { sanitizeSearchInput } from "../lib/utils";
 
export type BlogTagFilters = {
	search?: string;
};
 
export class BlogTagsDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	// ============================================================================
	// TAG CRUD
	// ============================================================================
 
	async findAll(
		filters: BlogTagFilters = {},
		offset = 0,
		limit = 100,
	): Promise<BlogTag[]> {
		const conditions = [];
 
		if (filters.search) {
			const sanitized = sanitizeSearchInput(filters.search);
			conditions.push(like(schema.blogTags.name, `%${sanitized}%`));
		}
 
		const query = this.db
			.select()
			.from(schema.blogTags)
			.orderBy(schema.blogTags.name)
			.limit(limit)
			.offset(offset);
 
		if (conditions.length > 0) {
			return query.where(and(...conditions));
		}
 
		return query;
	}
 
	async count(filters: BlogTagFilters = {}): Promise<number> {
		const conditions = [];
 
		if (filters.search) {
			const sanitized = sanitizeSearchInput(filters.search);
			conditions.push(like(schema.blogTags.name, `%${sanitized}%`));
		}
 
		const query = this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.blogTags);
 
		const result =
			conditions.length > 0
				? await query.where(and(...conditions))
				: await query;
 
		return result[0]?.count ?? 0;
	}
 
	async findById(id: string): Promise<BlogTag | undefined> {
		const result = await this.db
			.select()
			.from(schema.blogTags)
			.where(eq(schema.blogTags.id, id))
			.limit(1);
		return result[0];
	}
 
	async findBySlug(slug: string): Promise<BlogTag | undefined> {
		const result = await this.db
			.select()
			.from(schema.blogTags)
			.where(eq(schema.blogTags.slug, slug))
			.limit(1);
		return result[0];
	}
 
	async create(data: NewBlogTag): Promise<BlogTag> {
		const result = await this.db
			.insert(schema.blogTags)
			.values(data)
			.returning();
		return result[0];
	}
 
	async update(
		id: string,
		data: Partial<Omit<BlogTag, "id" | "dateCreated">>,
	): Promise<BlogTag | undefined> {
		const result = await this.db
			.update(schema.blogTags)
			.set(data)
			.where(eq(schema.blogTags.id, id))
			.returning();
		return result[0];
	}
 
	async delete(id: string): Promise<boolean> {
		const result = await this.db
			.delete(schema.blogTags)
			.where(eq(schema.blogTags.id, id))
			.returning();
		return result.length > 0;
	}
 
	async slugExists(slug: string, excludeId?: string): Promise<boolean> {
		const conditions = [eq(schema.blogTags.slug, slug)];
		if (excludeId) {
			conditions.push(sql`${schema.blogTags.id} != ${excludeId}`);
		}
		const result = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.blogTags)
			.where(and(...conditions));
		return (result[0]?.count ?? 0) > 0;
	}
 
	// ============================================================================
	// TAG ASSIGNMENTS
	// ============================================================================
 
	async findByBlogId(blogId: string): Promise<BlogTag[]> {
		const result = await this.db
			.select({
				id: schema.blogTags.id,
				name: schema.blogTags.name,
				slug: schema.blogTags.slug,
				dateCreated: schema.blogTags.dateCreated,
			})
			.from(schema.blogTagAssignments)
			.innerJoin(
				schema.blogTags,
				eq(schema.blogTagAssignments.tagId, schema.blogTags.id),
			)
			.where(eq(schema.blogTagAssignments.blogId, blogId));
		return result;
	}
 
	/**
	 * Bulk fetch tags for multiple blogs (N+1 optimization)
	 * @param blogIds Array of blog IDs
	 * @returns Map of blogId -> BlogTag[]
	 */
	async findByBlogIds(blogIds: string[]): Promise<Map<string, BlogTag[]>> {
		if (blogIds.length === 0) return new Map();
 
		const result = await this.db
			.select({
				blogId: schema.blogTagAssignments.blogId,
				id: schema.blogTags.id,
				name: schema.blogTags.name,
				slug: schema.blogTags.slug,
				dateCreated: schema.blogTags.dateCreated,
			})
			.from(schema.blogTagAssignments)
			.innerJoin(
				schema.blogTags,
				eq(schema.blogTagAssignments.tagId, schema.blogTags.id),
			)
			.where(inArray(schema.blogTagAssignments.blogId, blogIds));
 
		const map = new Map<string, BlogTag[]>();
		for (const row of result) {
			if (!map.has(row.blogId)) map.set(row.blogId, []);
			const tags = map.get(row.blogId);
			/* v8 ignore start -- V8 artifact: Map.get always returns value after set */
			if (tags) {
			/* v8 ignore stop */
				tags.push({
					id: row.id,
					name: row.name,
					slug: row.slug,
					dateCreated: row.dateCreated,
				});
			}
		}
		return map;
	}
 
	async addToBlog(data: NewBlogTagAssignment): Promise<void> {
		await this.db.insert(schema.blogTagAssignments).values(data);
	}
 
	async removeFromBlog(blogId: string, tagId: string): Promise<boolean> {
		const result = await this.db
			.delete(schema.blogTagAssignments)
			.where(
				and(
					eq(schema.blogTagAssignments.blogId, blogId),
					eq(schema.blogTagAssignments.tagId, tagId),
				),
			)
			.returning();
		return result.length > 0;
	}
 
	async removeAllFromBlog(blogId: string): Promise<void> {
		await this.db
			.delete(schema.blogTagAssignments)
			.where(eq(schema.blogTagAssignments.blogId, blogId));
	}
}