Openstatus www.openstatus.dev
at main 79 lines 2.2 kB view raw
1import { z } from "zod"; 2 3import { Events } from "@openstatus/analytics"; 4import { type SQL, and, eq, isNull } from "@openstatus/db"; 5import { 6 monitor, 7 selectWorkspaceSchema, 8 usersToWorkspaces, 9 workspace, 10} from "@openstatus/db/src/schema"; 11 12import { createTRPCRouter, protectedProcedure } from "../trpc"; 13 14export const workspaceRouter = createTRPCRouter({ 15 getWorkspace: protectedProcedure.query(async (opts) => { 16 const result = await opts.ctx.db.query.workspace.findFirst({ 17 where: eq(workspace.id, opts.ctx.workspace.id), 18 }); 19 20 return selectWorkspaceSchema.parse(result); 21 }), 22 23 get: protectedProcedure.query(async (opts) => { 24 const whereConditions: SQL[] = [eq(workspace.id, opts.ctx.workspace.id)]; 25 26 const result = await opts.ctx.db.query.workspace.findFirst({ 27 where: and(...whereConditions), 28 with: { 29 pages: { 30 with: { 31 pageComponents: true, 32 }, 33 }, 34 monitors: { 35 where: isNull(monitor.deletedAt), 36 }, 37 notifications: true, 38 }, 39 }); 40 41 return selectWorkspaceSchema.parse({ 42 ...result, 43 usage: { 44 monitors: result?.monitors?.length || 0, 45 notifications: result?.notifications?.length || 0, 46 pages: result?.pages?.length || 0, 47 pageComponents: 48 result?.pages?.flatMap((page) => page.pageComponents)?.length || 0, 49 // checks: result?.checks?.length || 0, 50 checks: 0, 51 }, 52 }); 53 }), 54 55 list: protectedProcedure.query(async (opts) => { 56 const result = await opts.ctx.db.query.usersToWorkspaces.findMany({ 57 where: eq(usersToWorkspaces.userId, opts.ctx.user.id), 58 with: { 59 workspace: true, 60 }, 61 }); 62 63 return selectWorkspaceSchema 64 .array() 65 .parse(result.map(({ workspace }) => workspace)); 66 }), 67 68 updateName: protectedProcedure 69 .meta({ track: Events.UpdateWorkspace }) 70 .input(z.object({ name: z.string() })) 71 .mutation(async (opts) => { 72 const whereConditions: SQL[] = [eq(workspace.id, opts.ctx.workspace.id)]; 73 74 await opts.ctx.db 75 .update(workspace) 76 .set({ name: opts.input.name, updatedAt: new Date() }) 77 .where(and(...whereConditions)); 78 }), 79});