lending-apy-fetcher-ts
Version:
TypeScript library for fetching APYs from DeFi lending protocols
94 lines • 3.63 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TheGraphClient = exports.HttpClient = void 0;
const types_1 = require("../types");
class HttpClient {
constructor(config) {
this.config = config;
}
async get(url, headers) {
return this.executeWithRetry(async () => {
const response = await fetch(url, {
method: 'GET',
headers: {
'User-Agent': this.config.userAgent,
'Content-Type': 'application/json',
...headers,
},
signal: AbortSignal.timeout(this.config.defaultTimeout),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
});
}
async post(url, data, headers) {
return this.executeWithRetry(async () => {
const response = await fetch(url, {
method: 'POST',
headers: {
'User-Agent': this.config.userAgent,
'Content-Type': 'application/json',
...headers,
},
body: data ? JSON.stringify(data) : undefined,
signal: AbortSignal.timeout(this.config.defaultTimeout),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
});
}
async executeWithRetry(operation) {
let lastError = new Error('Unknown error');
for (let attempt = 1; attempt <= this.config.retryAttempts; attempt++) {
try {
return await operation();
}
catch (error) {
lastError = error;
if (error.message?.includes('401') || error.message?.includes('403')) {
throw new types_1.AuthenticationError(`Authentication failed: ${error.message}`, undefined, error);
}
if (attempt === this.config.retryAttempts) {
break;
}
if (this.config.enableLogging) {
console.log(`[HTTP] Attempt ${attempt} failed, retrying in ${this.config.retryDelay}ms...`);
}
await this.delay(this.config.retryDelay);
}
}
throw new types_1.NetworkError(`Request failed after ${this.config.retryAttempts} attempts`, undefined, lastError);
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
exports.HttpClient = HttpClient;
class TheGraphClient {
constructor(endpoint, config) {
this.endpoint = endpoint;
this.config = config;
this.httpClient = new HttpClient(config);
}
async query(query, variables) {
try {
const response = await this.httpClient.post(this.endpoint, { query, variables });
if (response.errors && response.errors.length > 0) {
throw new Error(`GraphQL errors: ${JSON.stringify(response.errors)}`);
}
return response.data;
}
catch (error) {
if (error instanceof types_1.AuthenticationError || error instanceof types_1.NetworkError) {
throw error;
}
throw new types_1.NetworkError(`The Graph query failed: ${error}`, undefined, error);
}
}
}
exports.TheGraphClient = TheGraphClient;
//# sourceMappingURL=http.js.map