11import { LRUCache } from "lru-cache" ;
22
3+ import { FCCResponse } from "@/app/api/fcc-lookup/route" ;
4+
35interface ZippopotamPlace {
46 "place name" : string ; // city name
57 state : string ;
@@ -41,12 +43,43 @@ export async function fetchLocationFromZip(zipCode: string): Promise<string> {
4143
4244 const data = ( await response . json ( ) ) as ZippopotamResponse ;
4345 const place = data . places ?. [ 0 ] ;
44- if ( place ) {
45- const result = `${ place [ "place name" ] } , ${ place [ "state abbreviation" ] } ` ;
46- // Cache successful result
47- zipCodeCache . set ( zipCode , result ) ;
48- return result ;
46+ if ( ! place ) {
47+ // Cache empty string if no place found
48+ zipCodeCache . set ( zipCode , "" ) ;
49+ return "" ;
50+ }
51+
52+ // Query FCC API via our server-side API route to avoid CORS issues
53+ const fccAc = new AbortController ( ) ;
54+ const timeoutId2 = setTimeout ( ( ) => fccAc . abort ( ) , 5_000 ) ;
55+ try {
56+ const fccResponse = await fetch (
57+ `/api/fcc-lookup?latitude=${ place . latitude } &longitude=${ place . longitude } ` ,
58+ {
59+ signal : fccAc . signal ,
60+ } ,
61+ ) ;
62+ clearTimeout ( timeoutId2 ) ;
63+
64+ if ( fccResponse . ok ) {
65+ const fccData = ( await fccResponse . json ( ) ) as FCCResponse ;
66+
67+ // Use county name from FCC and state abbreviation
68+ if ( fccData . County && fccData . State ) {
69+ const result = `${ place [ "place name" ] } (${ fccData . County . name } county), ${ fccData . State . code } ` ;
70+ zipCodeCache . set ( zipCode , result ) ;
71+ return result ;
72+ }
73+ }
74+ } catch ( fccError ) {
75+ // If FCC API throws any error, fall back to zippopotam's city and state
76+ clearTimeout ( timeoutId2 ) ;
77+ console . warn ( "Error fetching from FCC API:" , fccError ) ;
4978 }
79+ // Fall back to zippopotam data if FCC fails
80+ const result = `${ place [ "place name" ] } , ${ place [ "state abbreviation" ] } ` ;
81+ zipCodeCache . set ( zipCode , result ) ;
82+ return result ;
5083 } catch ( error ) {
5184 clearTimeout ( timeoutId ) ;
5285 if ( error instanceof Error && error . name === "AbortError" ) {
@@ -55,8 +88,7 @@ export async function fetchLocationFromZip(zipCode: string): Promise<string> {
5588 console . warn ( "Error fetching city/state from zip code:" , error ) ;
5689 }
5790 }
58-
59- // Cache empty string if no place found or errors (including timeouts)
91+ // Cache empty string if errors
6092 zipCodeCache . set ( zipCode , "" ) ;
6193 return "" ;
6294}
0 commit comments