@gviper/alphavantage-api
Version:
TypeScript SDK for Alpha Vantage API with comprehensive type safety and all endpoint support
111 lines • 5.36 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AlphaVantageClient = void 0;
const axios_1 = __importDefault(require("axios"));
const https_proxy_agent_1 = require("https-proxy-agent");
const http_proxy_agent_1 = require("http-proxy-agent");
const errors_1 = require("./errors");
class AlphaVantageClient {
constructor(options) {
if (!options.apiKey) {
throw new errors_1.AlphaVantageError('API key is required');
}
this.apiKey = options.apiKey;
this.baseUrl = options.baseUrl || 'https://www.alphavantage.co/query';
this.timeout = options.timeout || 30000; // 30 seconds
this.retryAttempts = options.retryAttempts || 3;
this.retryDelay = options.retryDelay || 1000; // 1 second
// Create axios instance with proxy support
this.axiosInstance = this.createAxiosInstance();
}
createAxiosInstance() {
const config = {
timeout: this.timeout,
headers: {
'User-Agent': 'alphavantage-api/1.0.0',
},
};
// Add proxy support if proxy environment variables are set
const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy;
const httpProxy = process.env.HTTP_PROXY || process.env.http_proxy;
if (httpsProxy) {
config.httpsAgent = new https_proxy_agent_1.HttpsProxyAgent(httpsProxy);
console.error(`[PROXY] Using HTTPS proxy: ${httpsProxy}`);
}
if (httpProxy) {
config.httpAgent = new http_proxy_agent_1.HttpProxyAgent(httpProxy);
console.error(`[PROXY] Using HTTP proxy: ${httpProxy}`);
}
return axios_1.default.create(config);
}
async request(params) {
const requestParams = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined)
requestParams.append(key, String(value));
});
requestParams.append('apikey', this.apiKey);
let lastError;
for (let attempt = 0; attempt <= this.retryAttempts; attempt++) {
try {
const response = await this.axiosInstance.get(this.baseUrl, {
params: Object.fromEntries(requestParams.entries()),
});
const data = response.data;
// Handle API-specific errors
if (data['Error Message']) {
const errorMessage = data['Error Message'];
if (errorMessage.includes('Invalid API call') || errorMessage.includes('Invalid symbol')) {
throw new errors_1.AlphaVantageInvalidSymbolError(params.symbol || 'unknown');
}
throw new errors_1.AlphaVantageAPIError(errorMessage);
}
if (data['Note']) {
const note = data['Note'];
if (note.includes('API rate limit') || note.includes('frequency')) {
throw new errors_1.AlphaVantageRateLimitError(note);
}
throw new errors_1.AlphaVantageAPIError(note);
}
if (data['Information']) {
throw new errors_1.AlphaVantageAPIError(data['Information']);
}
return data;
}
catch (error) {
// Handle axios errors
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
lastError = new errors_1.AlphaVantageAPIError(`HTTP ${error.response.status}: ${error.response.statusText}`, error.response.status);
}
else if (error.request) {
// The request was made but no response was received
lastError = new errors_1.AlphaVantageNetworkError('No response received from server', error);
}
else if (error instanceof errors_1.AlphaVantageInvalidSymbolError ||
error instanceof errors_1.AlphaVantageRateLimitError ||
error instanceof errors_1.AlphaVantageAPIError) {
// Don't retry on certain errors
throw error;
}
else {
// Something happened in setting up the request that triggered an Error
lastError = new errors_1.AlphaVantageNetworkError('Request setup failed', error);
}
// If this is the last attempt, throw the error
if (attempt === this.retryAttempts) {
break;
}
// Wait before retrying
await new Promise(resolve => setTimeout(resolve, this.retryDelay * (attempt + 1)));
}
}
throw new errors_1.AlphaVantageNetworkError(`Request failed after ${this.retryAttempts + 1} attempts`, lastError || new Error('Unknown error'));
}
}
exports.AlphaVantageClient = AlphaVantageClient;
//# sourceMappingURL=client.js.map