Openstatus
www.openstatus.dev
1import { and, eq } from "@openstatus/db";
2import {
3 privateLocation,
4 privateLocationToMonitors,
5} from "@openstatus/db/src/schema";
6import { z } from "zod";
7
8import { createTRPCRouter, protectedProcedure } from "../trpc";
9
10export const privateLocationRouter = createTRPCRouter({
11 list: protectedProcedure.query(async (opts) => {
12 const privateLocations = await opts.ctx.db.transaction(async (tx) => {
13 return await tx.query.privateLocation.findMany({
14 where: eq(privateLocation.workspaceId, opts.ctx.workspace.id),
15 with: {
16 privateLocationToMonitors: {
17 with: { monitor: true },
18 },
19 },
20 });
21 });
22 const result = privateLocations.map((privateLocation) => ({
23 ...privateLocation,
24 monitors: privateLocation.privateLocationToMonitors
25 .map((m) => m.monitor)
26 .filter((m) => m !== null),
27 }));
28 return result;
29 }),
30 new: protectedProcedure
31 .input(
32 z.object({
33 name: z.string(),
34 monitors: z.array(z.number()),
35 token: z.string(),
36 }),
37 )
38 .mutation(async (opts) => {
39 return await opts.ctx.db.transaction(async (tx) => {
40 const _privateLocation = await tx
41 .insert(privateLocation)
42 .values({
43 name: opts.input.name,
44 token: opts.input.token,
45 workspaceId: opts.ctx.workspace.id,
46 })
47 .returning()
48 .get();
49
50 if (opts.input.monitors.length) {
51 await tx.insert(privateLocationToMonitors).values(
52 opts.input.monitors.map((monitorId) => ({
53 privateLocationId: _privateLocation.id,
54 monitorId,
55 })),
56 );
57 }
58 return _privateLocation;
59 });
60 }),
61 update: protectedProcedure
62 .input(
63 z.object({
64 id: z.number(),
65 name: z.string(),
66 monitors: z.array(z.number()),
67 }),
68 )
69 .mutation(async (opts) => {
70 return await opts.ctx.db.transaction(async (tx) => {
71 const _privateLocation = await tx
72 .update(privateLocation)
73 .set({ name: opts.input.name, updatedAt: new Date() })
74 .where(
75 and(
76 eq(privateLocation.id, opts.input.id),
77 eq(privateLocation.workspaceId, opts.ctx.workspace.id),
78 ),
79 )
80 .returning()
81 .get();
82
83 await tx
84 .delete(privateLocationToMonitors)
85 .where(
86 eq(
87 privateLocationToMonitors.privateLocationId,
88 _privateLocation.id,
89 ),
90 );
91
92 if (opts.input.monitors.length) {
93 await tx.insert(privateLocationToMonitors).values(
94 opts.input.monitors.map((monitorId) => ({
95 privateLocationId: _privateLocation.id,
96 monitorId,
97 })),
98 );
99 }
100
101 return _privateLocation;
102 });
103 }),
104 delete: protectedProcedure
105 .input(z.object({ id: z.number() }))
106 .mutation(async (opts) => {
107 console.log("delete private location", opts.input.id);
108 return await opts.ctx.db.transaction(async (tx) => {
109 await tx
110 .delete(privateLocation)
111 .where(
112 and(
113 eq(privateLocation.id, opts.input.id),
114 eq(privateLocation.workspaceId, opts.ctx.workspace.id),
115 ),
116 );
117 });
118 }),
119});