84 lines
2.6 KiB
TypeScript
Raw Normal View History

2025-05-18 12:22:22 +02:00
import { NextRequest, NextResponse } from "next/server";
2025-05-18 12:12:49 +02:00
import prisma from "@/app/prisma";
2025-05-20 17:40:29 +02:00
import Fuse from 'fuse.js';
import { Site } from "@/app/types";
2025-05-18 12:22:22 +02:00
export async function GET(request: NextRequest) {
const { searchParams } = request.nextUrl;
const currentPage = Number(searchParams.get("currentPage")) || 1;
2025-05-20 17:40:29 +02:00
const itemPerPage = Number(searchParams.get("itemPerPage")) || 10;
2025-05-18 12:45:31 +02:00
const search = searchParams.get("search") || "";
2025-05-18 12:22:22 +02:00
2025-05-18 12:12:49 +02:00
try {
2025-05-20 17:40:29 +02:00
if (!search) {
const skip = (currentPage - 1) * itemPerPage;
const take = itemPerPage;
const sites = await prisma.site.findMany({
skip,
take,
orderBy: {
name: 'asc',
2025-05-18 12:45:31 +02:00
},
2025-05-20 17:40:29 +02:00
include: {
networks: {
orderBy: {
name: 'asc',
},
},
2025-05-18 12:45:31 +02:00
},
2025-05-20 17:40:29 +02:00
});
const total = await prisma.site.count();
return NextResponse.json({ sites, total, currentPage, itemPerPage }, { status: 200 });
}
const allSites = await prisma.site.findMany({
2025-05-18 15:44:55 +02:00
include: {
2025-05-18 17:01:25 +02:00
networks: {
orderBy: {
name: 'asc',
},
},
2025-05-18 15:44:55 +02:00
},
2025-05-18 12:45:31 +02:00
});
2025-05-20 17:40:29 +02:00
const fuseOptions = {
includeScore: true,
threshold: 0.4,
keys: ['name', 'description', 'networks.name']
};
const fuse = new Fuse(allSites, fuseOptions);
const searchResults = fuse.search(search);
const filteredSites = searchResults.map(result => {
const item = result.item;
return {
...item,
id: String(item.id),
networks: item.networks?.map(network => ({
...network,
id: String(network.id),
siteId: String(network.siteId)
})) || []
} as Site;
2025-05-18 12:22:22 +02:00
});
2025-05-20 17:40:29 +02:00
const total = filteredSites.length;
const startIndex = (currentPage - 1) * itemPerPage;
const endIndex = startIndex + itemPerPage;
const paginatedSites = filteredSites.slice(startIndex, endIndex);
return NextResponse.json({
sites: paginatedSites,
total,
currentPage,
itemPerPage
}, { status: 200 });
2025-05-18 12:12:49 +02:00
} catch (error: any) {
2025-05-20 17:40:29 +02:00
console.error("Search error:", error);
2025-05-18 12:12:49 +02:00
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
}
}