Spaces:
Runtime error
Runtime error
File size: 1,843 Bytes
97dab2a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | // src/weather.service.ts
import { Injectable } from '@nestjs/common';
import axios from 'axios';
@Injectable()
export class WeatherApiService {
private readonly apiKey: string;
private readonly baseUrl1 = 'https://api.openweathermap.org/data/2.5/forecast';
private readonly baseUrl2 = 'https://api.openweathermap.org/data/2.5/weather';
constructor() {
this.apiKey = process.env.WEATHER_SERVICE_API_KEY || 'default';
//console.log('WEATHER_SERVICE_API_KEY:', this.apiKey);
}
async getCurrentWeather({ city, country }) {
const weatherApiUrl = `${this.baseUrl2}?q=${city}&appid=${this.apiKey}&units=metric`;
try {
const response = await axios.get(weatherApiUrl);
const data = response.data;
return {
city,
country,
temperature: data.main.temp,
condition: data.weather[0].description,
humidity: data.main.humidity,
windSpeed: data.wind.speed,
};
} catch (error) {
console.error('Error fetching weather data:', error);
throw new Error('Failed to fetch weather data: ' + error.message);
}
}
async getForecast({city, country, days}): Promise<any> {
const url = `${this.baseUrl1}?q=${encodeURIComponent(city)}&appid=${this.apiKey}&units=metric`;
try {
console.log(`Fetching weather forecast for city: ${city}`);
const response = await axios.get(url);
const forecasts = Array.from({ length: days }, (_, i) => ({
date: new Date(Date.now() + i * 86400000).toISOString().split('T')[0],
temperature: `${20 + i}°C`,
condition: i % 2 === 0 ? 'Sunny' : 'Cloudy',
}));
return { forecasts };
} catch (error) {
console.log(`Failed to fetch weather forecast: ${error.message}`, error.stack);
throw error;
}
}
}
|