-
Notifications
You must be signed in to change notification settings - Fork 269
Expand file tree
/
Copy pathroute.ts
More file actions
50 lines (41 loc) · 1.32 KB
/
Copy pathroute.ts
File metadata and controls
50 lines (41 loc) · 1.32 KB
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
import { getAuthSession } from "@/lib/auth";
import { db } from "@/lib/db";
import { SubredditValidator } from "@/lib/validators/subreddit";
// import z from "zod/lib";
import { z } from "zod";
export async function POST(req: Request) {
try {
const session = await getAuthSession()
if (!session?.user) {
return new Response('Unauthorized', { status: 401 })
}
const body = await req.json()
const { name } = SubredditValidator.parse(body)
const subredditExists = await db.subreddit.findFirst({
where: {
name,
},
})
if (subredditExists) {
return new Response('Subreddit already exists', { status: 409 })
}
const subreddit = await db.subreddit.create({
data: {
name,
creatorId: session.user.id,
},
})
await db.subscription.create({
data: {
userId: session.user.id,
subredditId: subreddit.id,
},
})
return new Response(subreddit.name)
} catch (error) {
if (error instanceof z.ZodError) {
return new Response(error.message, { status: 422 })
}
return new Response('Could not create subreddit', { status: 500 })
}
}