aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/server/repositories/deck.ts
blob: 77985a72c374a1ddfd960f9e4fd36c2af3dd58cb (plain)
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
import { and, eq, isNull, sql } from "drizzle-orm";
import { db } from "../db/index.js";
import { decks } from "../db/schema.js";
import type { Deck, DeckRepository } from "./types.js";

export const deckRepository: DeckRepository = {
	async findByUserId(userId: string): Promise<Deck[]> {
		const result = await db
			.select()
			.from(decks)
			.where(and(eq(decks.userId, userId), isNull(decks.deletedAt)));
		return result;
	},

	async findById(id: string, userId: string): Promise<Deck | undefined> {
		const result = await db
			.select()
			.from(decks)
			.where(
				and(
					eq(decks.id, id),
					eq(decks.userId, userId),
					isNull(decks.deletedAt),
				),
			);
		return result[0];
	},

	async create(data: {
		userId: string;
		name: string;
		description?: string | null;
		newCardsPerDay?: number;
	}): Promise<Deck> {
		const [deck] = await db
			.insert(decks)
			.values({
				userId: data.userId,
				name: data.name,
				description: data.description ?? null,
				newCardsPerDay: data.newCardsPerDay ?? 20,
			})
			.returning();
		if (!deck) {
			throw new Error("Failed to create deck");
		}
		return deck;
	},

	async update(
		id: string,
		userId: string,
		data: {
			name?: string;
			description?: string | null;
			newCardsPerDay?: number;
		},
	): Promise<Deck | undefined> {
		const result = await db
			.update(decks)
			.set({
				...data,
				updatedAt: new Date(),
				syncVersion: sql`${decks.syncVersion} + 1`,
			})
			.where(
				and(
					eq(decks.id, id),
					eq(decks.userId, userId),
					isNull(decks.deletedAt),
				),
			)
			.returning();
		return result[0];
	},

	async softDelete(id: string, userId: string): Promise<boolean> {
		const result = await db
			.update(decks)
			.set({
				deletedAt: new Date(),
				updatedAt: new Date(),
				syncVersion: sql`${decks.syncVersion} + 1`,
			})
			.where(
				and(
					eq(decks.id, id),
					eq(decks.userId, userId),
					isNull(decks.deletedAt),
				),
			)
			.returning({ id: decks.id });
		return result.length > 0;
	},
};