@@ -13,35 +13,48 @@ export const weatherRoute = Router();
1313 */
1414weatherRoute . get ( '/' , async ( req : Request , res : Response ) : Promise < void > => {
1515 try {
16- const { latitude, longitude } = req . query ;
17-
18- if ( ! latitude || ! longitude ) {
19- res . status ( StatusCodes . BAD_REQUEST ) . json ( {
20- message : 'Please provide both latitude and longitude as query parameters.'
21- } ) ;
16+ let latitude , longitude ;
17+ // Extract client IP (supports proxies)
18+ if ( ! req . query . latitude && ! req . query . longitude ) {
19+ const ip = req . headers [ 'x-forwarded-for' ] || req . socket . remoteAddress ;
20+
21+ console . log ( `Fetching location for IP: ${ ip } ` ) ;
22+
23+ // Fetch geolocation data using ip-api.com
24+ const geoResponse = await axios . get ( `http://ip-api.com/json/${ ip } ` ) ;
25+ const { lat, lon, city, country, status } = geoResponse . data ;
26+ latitude = lat ;
27+ longitude = lon ;
28+
29+ if ( status !== 'success' ) {
30+ res . status ( 400 ) . json ( { error : 'Unable to determine location from IP' } ) ;
31+ console . error ( `Error fetching weather: ${ ip } ` ) ;
32+ return ;
33+ }
34+ console . log ( `Determined location: ${ city } , ${ country } (${ lat } , ${ lon } )` ) ;
35+ } else {
36+ latitude = req . query . latitude ;
37+ longitude = req . query . longitude ;
2238 }
2339
24- // Construct the Open-Meteo API URL:
25- const apiUrl = `https://api.open-meteo.com/v1/forecast?latitude=${ latitude } &longitude=${ longitude } ¤t=temperature_2m,weathercode,windspeed_10m&daily=temperature_2m_max,temperature_2m_min,weathercode,sunrise,sunset&timezone=auto` ;
26-
27- // Fetch data from the Open-Meteo API using Axios
28- const { data, status } = await axios . get ( apiUrl ) ;
2940
30- // If status is not 200, treat it as an error
31- if ( status !== StatusCodes . OK ) {
32- res . status ( StatusCodes . BAD_REQUEST ) . json ( {
33- message : 'Failed to fetch data from Open-Meteo'
34- } ) ;
35- }
41+ // Fetch weather data from Open-Meteo
42+ const weatherResponse = await axios . get ( 'https://api.open-meteo.com/v1/forecast' , {
43+ params : {
44+ latitude : latitude ,
45+ longitude : longitude ,
46+ current : 'temperature_2m,weathercode,windspeed_10m' ,
47+ daily : 'temperature_2m_max,temperature_2m_min,weathercode,sunrise,sunset' ,
48+ timezone : 'auto'
49+ }
50+ } ) ;
51+ console . log ( weatherResponse . data ) ;
3652
37- // Return the JSON data from Open-Meteo
38- res . status ( StatusCodes . OK ) . json ( data ) ;
53+ res . json (
54+ weatherResponse . data
55+ ) ;
3956
4057 } catch ( error ) {
41- // Handle unexpected errors (e.g., network issues)
42- res . status ( StatusCodes . INTERNAL_SERVER_ERROR ) . json ( {
43- message : 'Error fetching weather data' ,
44- error : ( error as Error ) . message ,
45- } ) ;
58+ console . error ( 'Error fetching weather:' , error ) ;
4659 }
4760} ) ;
0 commit comments