|
| 1 | +import { getClientAddress, takeRateLimitToken } from "../_lib/rateLimit"; |
| 2 | +import { errorResponse, handleOptions, json, withCors } from "../_lib/http"; |
| 3 | +import type { Env } from "../_lib/types"; |
| 4 | + |
| 5 | +type NominatimResult = { |
| 6 | + place_id: number; |
| 7 | + display_name: string; |
| 8 | + lat: string; |
| 9 | + lon: string; |
| 10 | +}; |
| 11 | + |
| 12 | +const parsePerMinuteLimit = (raw: string | undefined, fallback: number): number => { |
| 13 | + const parsed = Number(raw ?? ""); |
| 14 | + if (!Number.isFinite(parsed)) return fallback; |
| 15 | + return Math.max(1, Math.floor(parsed)); |
| 16 | +}; |
| 17 | + |
| 18 | +const CACHE_TTL_SEC = 300; |
| 19 | + |
| 20 | +export const onRequestOptions: PagesFunction<Env> = async ({ request }) => handleOptions(request); |
| 21 | + |
| 22 | +export const onRequestGet: PagesFunction<Env> = async ({ request, env }) => { |
| 23 | + try { |
| 24 | + const url = new URL(request.url); |
| 25 | + const query = (url.searchParams.get("q") ?? "").trim(); |
| 26 | + |
| 27 | + if (!query) return withCors(request, json({ results: [] })); |
| 28 | + if (query.length < 3) { |
| 29 | + return withCors(request, json({ error: "Search query must be at least 3 characters." }, { status: 400 })); |
| 30 | + } |
| 31 | + |
| 32 | + const limitPerMinute = parsePerMinuteLimit(env.GEOCODE_RATE_LIMIT_PER_MINUTE, 20); |
| 33 | + const address = getClientAddress(request); |
| 34 | + const limiter = takeRateLimitToken({ key: `geocode:${address}`, limit: limitPerMinute }); |
| 35 | + if (!limiter.allowed) { |
| 36 | + return withCors( |
| 37 | + request, |
| 38 | + json( |
| 39 | + { error: "Geocode rate limit reached. Please wait and try again." }, |
| 40 | + { |
| 41 | + status: 429, |
| 42 | + headers: { |
| 43 | + "retry-after": String(limiter.retryAfterSec), |
| 44 | + }, |
| 45 | + }, |
| 46 | + ), |
| 47 | + ); |
| 48 | + } |
| 49 | + |
| 50 | + const normalized = query.toLowerCase(); |
| 51 | + const cacheUrl = new URL(request.url); |
| 52 | + cacheUrl.search = ""; |
| 53 | + cacheUrl.searchParams.set("q", normalized); |
| 54 | + const cacheKey = new Request(cacheUrl.toString(), { method: "GET" }); |
| 55 | + const cache = caches.default; |
| 56 | + const cached = await cache.match(cacheKey); |
| 57 | + if (cached) return withCors(request, cached); |
| 58 | + |
| 59 | + const upstream = new URL("https://nominatim.openstreetmap.org/search"); |
| 60 | + upstream.searchParams.set("q", query); |
| 61 | + upstream.searchParams.set("format", "jsonv2"); |
| 62 | + upstream.searchParams.set("limit", "6"); |
| 63 | + upstream.searchParams.set("addressdetails", "0"); |
| 64 | + |
| 65 | + const response = await fetch(upstream.toString(), { |
| 66 | + headers: { |
| 67 | + accept: "application/json", |
| 68 | + }, |
| 69 | + }); |
| 70 | + if (!response.ok) { |
| 71 | + throw new Error(`Geocode lookup failed (${response.status})`); |
| 72 | + } |
| 73 | + |
| 74 | + const payload = (await response.json()) as NominatimResult[]; |
| 75 | + const results = payload |
| 76 | + .map((item) => ({ |
| 77 | + id: String(item.place_id), |
| 78 | + label: item.display_name, |
| 79 | + lat: Number(item.lat), |
| 80 | + lon: Number(item.lon), |
| 81 | + })) |
| 82 | + .filter((item) => Number.isFinite(item.lat) && Number.isFinite(item.lon)); |
| 83 | + |
| 84 | + const apiResponse = json( |
| 85 | + { results }, |
| 86 | + { |
| 87 | + headers: { |
| 88 | + "cache-control": `public, max-age=${CACHE_TTL_SEC}`, |
| 89 | + }, |
| 90 | + }, |
| 91 | + ); |
| 92 | + await cache.put(cacheKey, apiResponse.clone()); |
| 93 | + return withCors(request, apiResponse); |
| 94 | + } catch (error) { |
| 95 | + return errorResponse(request, error, 500); |
| 96 | + } |
| 97 | +}; |
0 commit comments