diff --git a/src/app/api/guess/dataProvider.ts b/src/app/api/guess/dataProvider.ts new file mode 100644 index 0000000..d9aa06f --- /dev/null +++ b/src/app/api/guess/dataProvider.ts @@ -0,0 +1,59 @@ +import type { Match } from "@/types"; + +export async function findNorwegianPerson(input: string): Promise { + const apiUrl = `https://snl.no/api/v1/search?query=${encodeURIComponent(input)}&limit=5`; + const response = await fetch(apiUrl); + const data = await response.json(); + + function isNorwegianPerson(item: any): boolean { + // Must be a biography + if (item.article_type_id !== 2) return false; + + if (typeof item.rank !== "number" || item.rank <= 100) return false; + + // Must mention Norwegian-ness in any relevant field + const combinedText = [ + item.taxonomy_title || "", + item.subject_title || "", + item.first_sentences || "", + item.snippet || "", + ].join(" "); + return /(norsk|norske|norges|norge)/i.test(combinedText); + } + + // Filter for Norwegian biographies with strong match + const people = (data.hits || data).filter(isNorwegianPerson); + + if (people.length > 0) { + const person = people[0]; + const description = await (async () => { + try { + const articleJsonRes = await fetch(person.article_url_json); + const articleJson = await articleJsonRes.json(); + + if (articleJson.metadata && articleJson.metadata.occupation) { + return articleJson.metadata.occupation; + } else if (articleJson.subject_title) { + return articleJson.subject_title; + } + } catch (e) { + // fallback to undefined + } + return undefined; + })(); + + return { + input, + name: person.title || person.headword, + description, + correct: true, + }; + } else { + return { + input, + name: undefined, + description: undefined, + correct: false, + }; + } +} diff --git a/src/app/api/guess/route.ts b/src/app/api/guess/route.ts index b553637..d3012b4 100644 --- a/src/app/api/guess/route.ts +++ b/src/app/api/guess/route.ts @@ -1,7 +1,9 @@ +import type { Match } from "@/types"; import { NextResponse } from "next/server"; +import { findNorwegianPerson } from "./dataProvider"; export async function POST(request: Request) { const { input } = await request.json(); - const correct = input === "test" || input === "test2"; - return NextResponse.json({ input, name: input.toUpperCase(), correct, description: "title of person" }); + const match: Match = await findNorwegianPerson(input); + return NextResponse.json(match); }