Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

todos.ts

77 lines1.9 KB

1import { router, authedProcedure } from '@/lib/trpc'
2import { z } from 'zod'
3import { TRPCError } from '@trpc/server'
4import { eq, and, arrayContains } from 'drizzle-orm'
5import { todosTable, createTodoSchema, updateTodoSchema } from '@/db/schema'
6​
7export const todosRouter = router({
8 getAll: authedProcedure.query(async ({ ctx }) => {
9 const todos = await ctx.db
10 .select()
11 .from(todosTable)
12 .where(arrayContains(todosTable.user_ids, [ctx.session.user.id]))
13 return todos
14 }),
15​
16 create: authedProcedure
17 .input(createTodoSchema)
18 .mutation(async ({ ctx, input }) => {
19 const [newItem] = await ctx.db
20 .insert(todosTable)
21 .values(input)
22 .returning()
23 return newItem
24 }),
25​
26 update: authedProcedure
27 .input(
28 z.object({
29 id: z.number(),
30 data: updateTodoSchema,
31 })
32 )
33 .mutation(async ({ ctx, input }) => {
34 const [updatedItem] = await ctx.db
35 .update(todosTable)
36 .set(input.data)
37 .where(
38 and(
39 eq(todosTable.id, input.id),
40 arrayContains(todosTable.user_ids, [ctx.session.user.id])
41 )
42 )
43 .returning()
44​
45 if (!updatedItem) {
46 throw new TRPCError({
47 code: 'NOT_FOUND',
48 message: 'Todo not found or you do not have permission to update it',
49 })
50 }
51​
52 return updatedItem
53 }),
54​
55 delete: authedProcedure
56 .input(z.object({ id: z.number() }))
57 .mutation(async ({ ctx, input }) => {
58 const [deletedItem] = await ctx.db
59 .delete(todosTable)
60 .where(
61 and(
62 eq(todosTable.id, input.id),
63 arrayContains(todosTable.user_ids, [ctx.session.user.id])
64 )
65 )
66 .returning()
67​
68 if (!deletedItem) {
69 throw new TRPCError({
70 code: 'NOT_FOUND',
71 message: 'Todo not found or you do not have permission to delete it',
72 })
73 }
74​
75 return deletedItem
76 }),
77})