All files / dal slug-redirects.dal.ts

100% Statements 4/4
100% Branches 2/2
100% Functions 3/3
100% Lines 4/4

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                  9x                   6x                           4x                   4x      
// Data Access Layer for slug redirects
import { and, eq } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type { NewSlugRedirect, SlugRedirect } from "../db/schema";
 
export type SlugRedirectEntityType = "pro" | "project" | "room";
 
export class SlugRedirectsDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	/**
	 * Record that oldSlug of entityType/entityId has been superseded.
	 * Uses INSERT OR IGNORE (onConflictDoNothing) on the composite unique
	 * index (entity_type, old_slug) — idempotent across re-runs.
	 * The caller must call this BEFORE the slug UPDATE so that if the UPDATE
	 * fails the redirect row points at a still-live slug (harmless).
	 */
	async record(data: NewSlugRedirect): Promise<void> {
		await this.db
			.insert(schema.slugRedirects)
			.values(data)
			.onConflictDoNothing();
	}
 
	/**
	 * Look up a redirect row by entity type and old slug.
	 * Returns null when no history row exists for this slug.
	 */
	async findByOldSlug(
		entityType: SlugRedirectEntityType,
		oldSlug: string,
	): Promise<SlugRedirect | null> {
		const rows = await this.db
			.select()
			.from(schema.slugRedirects)
			.where(
				and(
					eq(schema.slugRedirects.entityType, entityType),
					eq(schema.slugRedirects.oldSlug, oldSlug),
				),
			)
			.limit(1);
		return rows[0] ?? null;
	}
}