Question 24
Question
Answer
class ApiClient {
constructor(baseUrl) {
this.baseUrl = baseUrl; // Your base API URL
}
async request(method, path, data = null, options = {}) {
const defaultOptions = {
retries: 3,
retryDelay: 1000, // Initial retry delay in milliseconds
timeout: 5000, // Timeout duration in milliseconds
};
options = { ...defaultOptions, ...options }; // Merge defaults with provided options
return new Promise((resolve, reject) => {
const controller = new AbortController(); // For cancellation
let retriesLeft = options.retries;
const makeRequest = async () => {
try {
const response = await fetch(`${this.baseUrl}${path}`, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
signal: controller.signal, // Pass cancellation signal to fetch
});
if (!response.ok) {
const error = await response.text();
throw new Error(`API Request Failed: ${error}`); // Handle non-successful responses
}
return resolve(await response.json());
} catch (err) {
if (retriesLeft > 0) {
console.warn(`Request failed, retrying... (${retriesLeft} attempts left)`);
retriesLeft--;
setTimeout(() => makeRequest(), options.retryDelay);
} else {
reject(err);
}
}
};
makeRequest(); // Initiate the first request
});
}
// Example API calls (you'd add more based on your API)
async getUsers() {
return this.request('GET', '/users');
}
async createUser(user) {
return this.request('POST', '/users', user);
}
}
// Usage Example:
const client = new ApiClient('https://api.example.com'); // Your API base URL
client.getUsers()
.then((data) => console.log(data))
.catch((error) => console.error('Error:', error));
Last updated