Open History to see the last commit
1import { router, authedProcedure } from '@/lib/trpc'
2import { z } from 'zod'
3import { TRPCError } from '@trpc/server'
4import { eq, and, sql } from 'drizzle-orm'
5import {
6 projectsTable,
7 createProjectSchema,
8 updateProjectSchema,
9} from '@/db/schema'
10
11export const projectsRouter = router({
12 getAll: authedProcedure.query(async ({ ctx }) => {
13 const projects = await ctx.db
14 .select()
15 .from(projectsTable)
16 .where(
17 sql`owner_id = ${ctx.session.user.id} OR ${ctx.session.user.id} = ANY(shared_user_ids)`
18 )
19 return projects
20 }),
21
22 create: authedProcedure
23 .input(createProjectSchema)
24 .mutation(async ({ ctx, input }) => {
25 if (input.owner_id !== ctx.session.user.id) {
26 throw new TRPCError({
27 code: 'FORBIDDEN',
28 message: 'You can only create projects you own',
29 })
30 }
31
32 const [newItem] = await ctx.db
33 .insert(projectsTable)
34 .values(input)
35 .returning()
36
37 return newItem
38 }),
39
40 update: authedProcedure
41 .input(
42 z.object({
43 id: z.number(),
44 data: updateProjectSchema,
45 })
46 )
47 .mutation(async ({ ctx, input }) => {
48 const [updatedItem] = await ctx.db
49 .update(projectsTable)
50 .set(input.data)
51 .where(
52 and(
53 eq(projectsTable.id, input.id),
54 eq(projectsTable.owner_id, ctx.session.user.id)
55 )
56 )
57 .returning()
58
59 if (!updatedItem) {
60 throw new TRPCError({
61 code: 'NOT_FOUND',
62 message:
63 'Project not found or you do not have permission to update it',
64 })
65 }
66
67 return updatedItem
68 }),
69
70 delete: authedProcedure
71 .input(z.object({ id: z.number() }))
72 .mutation(async ({ ctx, input }) => {
73 const [deletedItem] = await ctx.db
74 .delete(projectsTable)
75 .where(
76 and(
77 eq(projectsTable.id, input.id),
78 eq(projectsTable.owner_id, ctx.session.user.id)
79 )
80 )
81 .returning()
82
83 if (!deletedItem) {
84 throw new TRPCError({
85 code: 'NOT_FOUND',
86 message:
87 'Project not found or you do not have permission to delete it',
88 })
89 }
90
91 return deletedItem
92 }),
93})