48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
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" },
|
||
});
|
||
};
|