Files
fuz-site/src/pages/api/cities-autocomplete.ts

48 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { APIRoute } from "astro";
import Database from "better-sqlite3";
// 🔥 Funkcja normalizująca — identyczna jak w C#
function normalize(input: string): string {
return input
.normalize("NFD")
.replace(/\p{Diacritic}/gu, "") // usuwa ogonki
.toLowerCase();
}
type CityRow = {
city: string;
};
export const GET: APIRoute = async ({ request }) => {
const url = new URL(request.url);
const q = url.searchParams.get("q")?.trim() || "";
if (q.length < 2) {
return new Response(JSON.stringify([]), {
headers: { "Content-Type": "application/json" },
});
}
const db = new Database("./src/data/ServicesRange.db", { readonly: true });
// 🔥 Pobieramy wszystkie miasta (jest ich mało to działa błyskawicznie)
const stmt = db.prepare(`
SELECT DISTINCT city
FROM ranges
`);
const rows = stmt.all() as CityRow[];
// 🔥 Normalizujemy po stronie Node — ZERO problemów z kolacją SQLite
const pattern = normalize(q);
const filtered = rows
.filter((row) => normalize(row.city).includes(pattern))
.slice(0, 20) // LIMIT 20
.map((r) => r.city);
return new Response(JSON.stringify(filtered), {
headers: { "Content-Type": "application/json" },
});
};