feat: page and limit params in mii list route

This commit is contained in:
trafficlunar 2025-04-12 22:37:52 +01:00
parent 2e4611520d
commit cc0b628048

View file

@ -4,7 +4,7 @@ import { z } from "zod";
import { auth } from "@/lib/auth"; import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma"; import { prisma } from "@/lib/prisma";
import { nameSchema, tagsSchema } from "@/lib/schemas"; import { nameSchema } from "@/lib/schemas";
const searchSchema = z.object({ const searchSchema = z.object({
query: nameSchema.optional(), query: nameSchema.optional(),
@ -18,11 +18,25 @@ const searchSchema = z.object({
.map((tag) => tag.trim()) .map((tag) => tag.trim())
.filter((tag) => tag.length > 0) .filter((tag) => tag.length > 0)
), ),
// todo: incorporate tagsSchema
// Profiles
userId: z.coerce userId: z.coerce
.number({ message: "User ID must be valid" }) .number({ message: "User ID must be a number" })
.int({ message: "User ID must be an integer" }) .int({ message: "User ID must be an integer" })
.positive({ message: "User ID must be valid" }) .positive({ message: "User ID must be valid" })
.optional(), .optional(),
// Pages
limit: z.coerce
.number({ message: "Limit must be a number" })
.int({ message: "Limit must be an integer" })
.min(1, { message: "Limit must be at least 1" })
.max(100, { message: "Limit cannot be more than 100" })
.optional(),
page: z.coerce
.number({ message: "Page must be a number" })
.int({ message: "Page must be an integer" })
.min(1, { message: "Page must be at least 1" })
.optional(),
}); });
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
@ -31,7 +45,7 @@ export async function GET(request: NextRequest) {
const parsed = searchSchema.safeParse(Object.fromEntries(request.nextUrl.searchParams)); const parsed = searchSchema.safeParse(Object.fromEntries(request.nextUrl.searchParams));
if (!parsed.success) return NextResponse.json({ error: parsed.error.errors[0].message }, { status: 400 }); if (!parsed.success) return NextResponse.json({ error: parsed.error.errors[0].message }, { status: 400 });
const { query, sort, tags, userId } = parsed.data; const { query, sort, tags, userId, page = 0, limit = 20 } = parsed.data;
const where: Prisma.MiiWhereInput = { const where: Prisma.MiiWhereInput = {
// Searching // Searching
@ -78,7 +92,7 @@ export async function GET(request: NextRequest) {
const [totalCount, filteredCount, list] = await Promise.all([ const [totalCount, filteredCount, list] = await Promise.all([
prisma.mii.count({ where: userId ? { userId } : {} }), prisma.mii.count({ where: userId ? { userId } : {} }),
prisma.mii.count({ where }), prisma.mii.count({ where }),
prisma.mii.findMany({ where, orderBy, select }), prisma.mii.findMany({ where, orderBy, select, skip: (page - 1) * limit, take: limit }),
]); ]);
return NextResponse.json({ return NextResponse.json({