aboutsummaryrefslogtreecommitdiff
path: root/apps/web/app/api/spaces/route.ts
blob: e85e07ede1430d1bf06cddf8e10403e4b3e1e8c9 (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
80
81
82
83
84
import { db } from "@/server/db";
import { space } from "@/server/db/schema";
import { eq } from "drizzle-orm";
import { NextRequest, NextResponse } from "next/server";
import { ensureAuth } from "../ensureAuth";
import { z } from "zod";

export const runtime = "edge";

export async function GET(req: NextRequest) {
	const session = await ensureAuth(req);

	if (!session) {
		return new Response("Unauthorized", { status: 401 });
	}

	const spaces = await db
		.select()
		.from(space)
		.where(eq(space.user, session.user.id))
		.all();

	// We want to slowly move away from this pattern and return `new Response` directly
	return NextResponse.json(
		{
			message: "OK",
			data: spaces,
		},
		{ status: 200 },
	);
}

export async function POST(req: NextRequest) {
	const session = await ensureAuth(req);

	if (!session) {
		return new Response("Unauthorized", { status: 401 });
	}

	const expectedInput = z.object({
		name: z.string(),
	});

	const jsonRequest = await req.json();

	const validated = expectedInput.safeParse(jsonRequest);
	if (!validated.success) {
		return new Response(
			JSON.stringify({ success: false, error: validated.error }),
			{
				status: 400,
			},
		);
	}

	const newSpace = await db.insert(space).values({
		name: validated.data.name,
		createdAt: new Date(),
		user: session.user.id,
	});

	return new Response(JSON.stringify({ success: true, data: newSpace }), {
		status: 200,
	});
}

export const DELETE = async (req: NextRequest) => {
	const session = await ensureAuth(req);

	if (!session) {
		return new Response("Unauthorized", { status: 401 });
	}

	const url = new URL(req.url);
	const spaceId = url.searchParams.get("space");

	if (!spaceId) {
		return new Response("Invalid space id", { status: 400 });
	}

	await db.delete(space).where(eq(space.id, parseInt(spaceId)));

	return new Response(JSON.stringify({ success: true }), { status: 200 });
};