Weather/app/services/weatherApi.ts

80 lines
2.1 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import axios,{type AxiosInstance,AxiosError} from 'axios';
import { type WeatherData } from '@/store/weatherStore';
const API_KEY = '0c4679ac2decfe6a756aa09e61f42dc1';
const BASE_URL = 'http://api.weatherstack.com';
const apiClient: AxiosInstance = axios.create({
baseURL: BASE_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
});
apiClient.interceptors.request.use(
(config) => {
config.params = {...config.params, access_key: API_KEY };
if (process.env.NODE_ENV === 'development'){
console.log('API Request:', config.method ?.toUpperCase(), config.url);
}
return config;
},
(error) => {
console.error('Request Error:' ,error);
return Promise.reject(error);
}
);
apiClient.interceptors.response.use(
(response) => {
if (response.data && response.data.error){
const error = response.data.error;
console.error('API Error:', error);
throw new Error(error.info || '请求失效');
}
if (process.env.NODE_ENV === 'development'){
console.log('API Response:', response.config.url,response.data);
}
return response;
},
(error :AxiosError)=>{
console.error('Response Error:',error.message);
if (error.response) {
const status = error.response.status;
if (status === 404) {
throw new Error('未找到该城市的天气信息');
} else if (status === 401) {
throw new Error('API认证失败请检查API');
} else if (status === 403) {
throw new Error('请检查API密钥是否正确');
}
}
else if (error.request) {
throw new Error('网络连接失败');
}
else {
return (('配置错误'))
}
}
);
export class WeatherApi {
static async getCurrentWeather(city: string): Promise<WeatherData> {
try {
const response = await apiClient.get<WeatherData>('/current',{
params:{query :city} ,
});
return response.data;
}catch (error){
throw error;
}
}
}
export default WeatherApi;