All files / dal ho-mood-board-shares.dal.ts

100% Statements 13/13
100% Branches 6/6
100% Functions 7/7
100% Lines 11/11

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              11x             2x 2x                       2x                   2x                 3x 2x                   2x       2x         2x       1x              
import { and, eq, inArray, isNull } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import type * as schema from "../db/schema";
import { hoMoodBoardShares } from "../db/schema";
import { generateShareToken } from "../lib/share-token";
 
export class HoMoodBoardSharesDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	async create(input: {
		boardId: string;
		createdByUser: string;
		userName: string;
	}) {
		const id = generateShareToken(input.userName);
		return this.db
			.insert(hoMoodBoardShares)
			.values({
				id,
				boardId: input.boardId,
				createdByUser: input.createdByUser,
			})
			.returning()
			.get();
	}
 
	async findActiveByBoardId(boardId: string) {
		const row = await this.db
			.select()
			.from(hoMoodBoardShares)
			.where(
				and(
					eq(hoMoodBoardShares.boardId, boardId),
					isNull(hoMoodBoardShares.revokedAt),
				),
			)
			.get();
		return row ?? null;
	}
 
	/**
	 * Batch-resolve which of the given boardIds have an active (non-revoked)
	 * share row. Used by GET /mood-boards to decorate owned boards with
	 * `hasActiveShare` in a single query instead of N per-board lookups.
	 */
	async findActiveBoardIds(boardIds: string[]): Promise<Set<string>> {
		if (boardIds.length === 0) return new Set();
		const rows = await this.db
			.select({ boardId: hoMoodBoardShares.boardId })
			.from(hoMoodBoardShares)
			.where(
				and(
					inArray(hoMoodBoardShares.boardId, boardIds),
					isNull(hoMoodBoardShares.revokedAt),
				),
			)
			.all();
		return new Set(rows.map((r) => r.boardId));
	}
 
	async findByToken(token: string) {
		const row = await this.db
			.select()
			.from(hoMoodBoardShares)
			.where(eq(hoMoodBoardShares.id, token))
			.get();
		return row ?? null;
	}
 
	async revoke(token: string) {
		return this.db
			.update(hoMoodBoardShares)
			.set({ revokedAt: new Date() })
			.where(eq(hoMoodBoardShares.id, token))
			.run();
	}
}