rui-weather-service-api
Version:
Weather API service with OpenWeatherMap integration - includes both standalone API and MCP server
67 lines • 2.5 kB
JavaScript
import axios from 'axios';
import https from 'https';
import config from '../config/index.js';
// Create a custom Axios instance with configuration
const createHttpClient = () => {
return axios.create({
baseURL: config.baseUrl,
timeout: config.timeout,
httpsAgent: new https.Agent({
rejectUnauthorized: config.rejectUnauthorized
})
});
};
// HTTP client instance
const httpClient = createHttpClient();
/**
* Updates the HTTP client configuration
*/
export function updateHttpClientConfig() {
httpClient.defaults.baseURL = config.baseUrl;
httpClient.defaults.timeout = config.timeout;
httpClient.defaults.httpsAgent = new https.Agent({
rejectUnauthorized: config.rejectUnauthorized
});
}
/**
* Makes a HTTP request with retry capability
* @param url Request URL
* @param params Request parameters
* @param maxRetries Maximum number of retry attempts
* @returns Promise with response data
*/
export async function fetchWithRetry(url, params = {}, maxRetries = config.maxRetries ?? 3) {
let lastError = null;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
console.log(`Attempt ${attempt}: Fetching data from ${url}...`);
const response = await httpClient.get(url, { params });
console.log('Data retrieved successfully');
return response.data;
}
catch (error) {
lastError = error;
console.error(`Attempt ${attempt} failed: ${error.message}`);
// Check if we should retry
if (attempt < maxRetries) {
// Exponential backoff with jitter
const delay = Math.min(1000 * Math.pow(2, attempt - 1) + Math.random() * 1000, 10000);
console.log(`Retrying in ${Math.round(delay)}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
// Create a custom error with more details
const weatherError = new Error(`Failed after ${maxRetries} attempts: ${lastError?.message}`);
weatherError.isWeatherError = true;
if (lastError && 'response' in lastError) {
const axiosError = lastError;
if (axiosError.response) {
weatherError.statusCode = axiosError.response.status;
weatherError.code = axiosError.response.data?.cod;
}
}
throw weatherError;
}
export default httpClient;
//# sourceMappingURL=http-client.js.map