Skip to content

Commit 912f0b3

Browse files
Added pagination to messages api route.
1 parent 03f6766 commit 912f0b3

File tree

1 file changed

+30
-10
lines changed

1 file changed

+30
-10
lines changed

src/app/api/reddit/messages/route.ts

+30-10
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,35 @@
1-
import { NextResponse } from 'next/server'
1+
import { NextRequest, NextResponse } from 'next/server'
22
import prisma from '@/lib/db'
33

4-
export async function GET(request: Request) {
5-
const { searchParams } = new URL(request.url)
6-
const type = searchParams.get('type')
4+
export async function GET(request: NextRequest) {
5+
try {
6+
// Parse query parameters for pagination
7+
const { searchParams } = new URL(request.url)
8+
const page = parseInt(searchParams.get('page') || '1', 10)
9+
const pageSize = parseInt(searchParams.get('pageSize') || '10', 10)
10+
const type = searchParams.get('type')
711

8-
const messages = await prisma.redditMessage.findMany({
9-
where: type ? { type } : undefined,
10-
orderBy: { createdAt: 'desc' },
11-
take: 50,
12-
})
12+
// Calculate skip value
13+
const skip = (page - 1) * pageSize
1314

14-
return NextResponse.json(messages)
15+
const messages = await prisma.redditMessage.findMany({
16+
where: type ? { type } : undefined,
17+
orderBy: { createdAt: 'desc' },
18+
skip,
19+
take: pageSize,
20+
})
21+
22+
// Optionally, get the total number of posts to return along with pagination info
23+
const totalCount = await prisma.redditMessage.count()
24+
25+
return NextResponse.json({
26+
data: messages,
27+
page,
28+
pageSize,
29+
totalCount,
30+
})
31+
} catch (error) {
32+
// Handle any errors
33+
return NextResponse.json({ error: (error as Error).message }, { status: 500 })
34+
}
1535
}

0 commit comments

Comments
 (0)