-
Notifications
You must be signed in to change notification settings - Fork 269
Expand file tree
/
Copy pathroute.ts
More file actions
82 lines (68 loc) · 2.12 KB
/
Copy pathroute.ts
File metadata and controls
82 lines (68 loc) · 2.12 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
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
import { getAuthSession } from "@/lib/auth"
import { db } from "@/lib/db"
import { z } from "zod"
export async function GET(req: Request) {
const url = new URL(req.url)
const session = await getAuthSession()
let followedCommunitiesIds: string[] = []
if (session) {
const followedCommunities = await db.subscription.findMany({
where: {
userId: session.user.id,
},
include: {
subreddit: true,
},
})
followedCommunitiesIds = followedCommunities.map(
({ subreddit }) => subreddit.id
)
}
try {
const { limit, page, subredditName } = z.object({
limit: z.string(),
page: z.string(),
subredditName: z.string().nullish().optional(),
}).parse({
subredditName: url.searchParams.get('subredditName'),
limit: url.searchParams.get('limit'),
page: url.searchParams.get('page'),
})
let whereClause = {}
if (subredditName) {
whereClause = {
subreddit: {
name: subredditName,
}
}
} else if (session) {
whereClause = {
subreddit: {
id: {
in: followedCommunitiesIds,
}
}
}
}
const posts = await db.post.findMany({
take: parseInt(limit),
skip: (parseInt(page) - 1) * parseInt(limit),
orderBy: {
createdAt: 'desc'
},
include: {
subreddit: true,
votes: true,
author: true,
comments: true,
},
where: whereClause,
})
return new Response(JSON.stringify(posts))
} catch (error) {
if (error instanceof z.ZodError) {
return new Response('Invalid request data passed', { status: 422 })
}
return new Response('Could not fetch more post, please try again later', { status: 500 })
}
}