-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodos.service.ts
50 lines (41 loc) · 1.29 KB
/
todos.service.ts
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
import { Injectable, Inject } from '@nestjs/common';
import { DB } from '@/db';
import { todos } from '@/db/schema';
import { z } from "@/zod-nestjs";
import { eq } from "drizzle-orm";
export type Todo = typeof todos.$inferSelect;
export const upsertTodoSchema = z.object({
title: z.string().min(1),
});
@Injectable()
export class TodosService {
constructor(@Inject("DB") private db: DB) {}
async getTodos() {
return this.db.select().from(todos);
}
async create(todoArgs: z.infer<typeof upsertTodoSchema>) {
const todoData: typeof todos.$inferInsert = {
id: crypto.randomUUID(),
title: todoArgs.title,
};
return this.db.insert(todos).values(todoData).returning();
}
async update(id: string, todoArgs: z.infer<typeof upsertTodoSchema>) {
const updatedTodo = await this.db.update(todos)
.set(todoArgs)
.where(eq(todos.id, id))
.returning();
return updatedTodo[0];
}
async toggle(id: string) {
const [currentTodo] = await this.db.select().from(todos).where(eq(todos.id, id));
if (!currentTodo) {
throw new Error('Todo not found');
}
const updatedTodo = await this.db.update(todos)
.set({ completed: !currentTodo.completed ? 1 : 0 })
.where(eq(todos.id, id))
.returning();
return updatedTodo[0];
}
}