import { http, HttpResponse } from "msw"; import Fuse from "fuse.js"; import fruits from "./data/fruits.json"; // Define the interface for the fruit item structure interface Fruit { name: string; category: string; description: string; } // Create a Fuse instance for searching fruits const fuse = new Fuse(fruits, { keys: ["name", "category", "description"], threshold: 0.3, distance: 1, }); // Define the handlers for the API endpoints export const handlers = [ http.get("http://localhost:4004/api/fruits", async ({ request }) => { const url = new URL(request.url); const query = url.searchParams.get("query") || ""; const page = parseInt(url.searchParams.get("page") || "1", 10); const pageSize = parseInt(url.searchParams.get("page_size") || "10", 10); // Perform the search using Fuse.js const filteredItems = query ? fuse.search(query).map(({ item }) => item) : fruits; // Pagination logic const totalResults = filteredItems.length; const totalPages = Math.ceil(totalResults / pageSize); // Ensure the requested page is within bounds const currentPage = Math.max(1, Math.min(page, totalPages)); const startIdx = (currentPage - 1) * pageSize; const items = filteredItems.slice(startIdx, startIdx + pageSize); return HttpResponse.json({ totalResults, totalPages, items, }); }), ];