52 lines
1.4 KiB
TypeScript
52 lines
1.4 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { prisma } from '@/lib/db/prisma';
|
|
import { animalFilterSchema } from '@/lib/validations/animal';
|
|
|
|
export async function GET(request: Request) {
|
|
const { searchParams } = new URL(request.url);
|
|
|
|
const parsed = animalFilterSchema.safeParse(
|
|
Object.fromEntries(searchParams.entries())
|
|
);
|
|
|
|
if (!parsed.success) {
|
|
return NextResponse.json(
|
|
{ error: 'Parâmetros inválidos.', details: parsed.error.flatten() },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const { district, species, sex, sterilized, urgent, status, page, limit } =
|
|
parsed.data;
|
|
|
|
const where = {
|
|
...(species && { species }),
|
|
...(sex && { sex }),
|
|
...(sterilized !== undefined && { sterilized }),
|
|
...(urgent !== undefined && { urgent }),
|
|
status: status ?? 'AVAILABLE',
|
|
...(district && {
|
|
shelter: { district: { contains: district, mode: 'insensitive' as const } },
|
|
}),
|
|
};
|
|
|
|
const [animals, total] = await Promise.all([
|
|
prisma.animal.findMany({
|
|
where,
|
|
include: {
|
|
photos: { where: { isPrimary: true }, take: 1 },
|
|
shelter: { select: { id: true, name: true, district: true } },
|
|
},
|
|
orderBy: [{ urgent: 'desc' }, { createdAt: 'desc' }],
|
|
skip: (page - 1) * limit,
|
|
take: limit,
|
|
}),
|
|
prisma.animal.count({ where }),
|
|
]);
|
|
|
|
return NextResponse.json({
|
|
animals,
|
|
pagination: { page, limit, total, pages: Math.ceil(total / limit) },
|
|
});
|
|
}
|