mtg-visual-search/app/api/route.tsx

38 lines
1.1 KiB
TypeScript

import data from "@/data.json"
import { CardType } from "@/types/types"
import { NextRequest } from "next/server"
const cardData = data as CardType[]
export const dynamic = "force-dynamic" // defaults to auto
export async function GET(request: NextRequest) {
// get search query from request
const search = request.nextUrl.searchParams.get("search") || ""
if (!search) {
return Response.json([])
}
console.log(search)
const cleanedSearch = search.replace(/[^a-zA-Z\s]/g, "").toLowerCase()
const searchWords = cleanedSearch.split(/\s+/)
const filteredData = cardData.filter((card) => {
let captionArray = card.caption?.toLowerCase().split(/[^a-z]/)
if (!captionArray) {
return false
}
const words = searchWords.filter((word) => captionArray.includes(word))
if (words.length) {
card.rank = 999999
for (const word of words) {
const index = captionArray.indexOf(word)
if (index && index < card.rank) {
card.rank = index
}
}
return true
}
return false
})
filteredData.sort((a, b) => a.rank! - b.rank!)
return Response.json(filteredData)
}