aboutsummaryrefslogtreecommitdiff
path: root/packages/web/src/server/api/routers/project.ts
blob: c76070d7b99fafd9e0e5446c0d6b0ef4d7e7ef3a (plain) (blame)
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { SupabaseProjectStore } from "@imemio/sdk";
import { z } from "zod";
import { createClient } from "~/lib/supabase/server";
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";

const globalProjectName = "global";
export const projectRouter = createTRPCRouter({
	list: protectedProcedure.query(async ({ ctx: context }) => {
		const supabaseClient = await createClient();
		const projectStore = new SupabaseProjectStore(
			supabaseClient,
			context.user.id,
		);
		const result = await projectStore.list();

		if (!result.success) {
			return [];
		}

		return result.value;
	}),

	create: protectedProcedure
		.input(
			z.object({
				name: z.string().min(1),
				description: z.string().optional(),
				isGlobal: z.boolean().optional().default(false),
			}),
		)
		.mutation(async ({ ctx: context, input }) => {
			const supabaseClient = await createClient();
			const projectStore = new SupabaseProjectStore(
				supabaseClient,
				context.user.id,
			);
			const result = await projectStore.create({
				name: input.name,
				description: input.description,
				isGlobal: input.isGlobal,
			});

			if (!result.success) {
				throw new Error("Failed to create project");
			}

			return result.value;
		}),

	getOrCreateGlobal: protectedProcedure.query(async ({ ctx: context }) => {
		const supabaseClient = await createClient();
		const projectStore = new SupabaseProjectStore(
			supabaseClient,
			context.user.id,
		);
		const listResult = await projectStore.list();

		if (listResult.success) {
			const existingGlobal = listResult.value.find(
				(project) => project.isGlobal,
			);

			if (existingGlobal) {
				return existingGlobal;
			}
		}

		const createResult = await projectStore.create({
			name: globalProjectName,
			isGlobal: true,
		});

		if (!createResult.success) {
			throw new Error("Failed to create global project");
		}

		return createResult.value;
	}),
});