API INTEGRATION PATTERNS
Ebaycclone Admin Panel
This document provides comprehensive information about API integration patterns used in the Ebaycclone Admin Panel, including HTTP client configuration, request/response handling, error management, and performance optimization strategies.
Architectural Design Credit and Contact Information
The architectural design of this API integration system is credited to Mindbricks Genesis Engine.
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this API integration system.
Documentation Scope
This guide covers the complete API integration patterns within the Ebaycclone Admin Panel. It includes HTTP client configuration, request/response handling, error management, caching strategies, and performance optimization techniques.
Intended Audience
This documentation is intended for frontend developers, API integrators, and system architects who need to understand, implement, or maintain API integration patterns within the admin panel.
HTTP Client Architecture
Service-Specific Axios Instances
AuctionOffer Axios Configuration
import axios from 'axios';
import { CONFIG } from 'src/global-config';
const auctionOfferAxiosInstance = axios.create({
baseURL: CONFIG.auctionOfferServiceUrl
});
auctionOfferAxiosInstance.interceptors.response.use(
(response) => response,
(error) => Promise.reject((error.response && error.response.data) || 'Something went wrong!')
);
export default auctionOfferAxiosInstance;
Fetcher Utility
export const fetcher = async (args) => {
try {
const [url, config] = Array.isArray(args) ? args : [args];
const res = await auctionOfferAxiosInstance.get(url, { ...config });
return res.data;
} catch (error) {
console.error('Failed to fetch:', error);
throw error;
}
};
Service Endpoints
export const auctionOfferEndpoints = {
auctionOfferOffer: {
updateAuctionOfferOffer: '/v1/auctionofferoffers/:auctionOfferOfferId'
,
getAuctionOfferOffer: '/v1/auctionofferoffers/:auctionOfferOfferId'
,
listAuctionOfferOffers: '/v1/auctionofferoffers'
,
createAuctionOfferOffer: '/v1/auctionofferoffers'
,
deleteAuctionOfferOffer: '/v1/auctionofferoffers/:auctionOfferOfferId'
},
auctionOfferBid: {
createAuctionOfferBid: '/v1/auctionofferbids'
,
getAuctionOfferBid: '/v1/auctionofferbids/:auctionOfferBidId'
,
updateAuctionOfferBid: '/v1/auctionofferbids/:auctionOfferBidId'
,
listAuctionOfferBids: '/v1/auctionofferbids'
,
deleteAuctionOfferBid: '/v1/auctionofferbids/:auctionOfferBidId'
}
};
CategoryManagement Axios Configuration
import axios from 'axios';
import { CONFIG } from 'src/global-config';
const categoryManagementAxiosInstance = axios.create({
baseURL: CONFIG.categoryManagementServiceUrl
});
categoryManagementAxiosInstance.interceptors.response.use(
(response) => response,
(error) => Promise.reject((error.response && error.response.data) || 'Something went wrong!')
);
export default categoryManagementAxiosInstance;
Fetcher Utility
export const fetcher = async (args) => {
try {
const [url, config] = Array.isArray(args) ? args : [args];
const res = await categoryManagementAxiosInstance.get(url, { ...config });
return res.data;
} catch (error) {
console.error('Failed to fetch:', error);
throw error;
}
};
Service Endpoints
export const categoryManagementEndpoints = {
category: {
deleteCategory: '/v1/categories/:categoryId'
,
getCategory: '/v1/categories/:categoryId'
,
listCategories: '/v1/categories'
,
updateCategory: '/v1/categories/:categoryId'
,
createCategory: '/v1/categories'
},
subcategory: {
getSubcategory: '/v1/subcategories/:subcategoryId'
,
updateSubcategory: '/v1/subcategories/:subcategoryId'
,
listSubcategories: '/v1/subcategories'
,
deleteSubcategory: '/v1/subcategories/:subcategoryId'
,
createSubcategory: '/v1/subcategories'
}
};
Messaging Axios Configuration
import axios from 'axios';
import { CONFIG } from 'src/global-config';
const messagingAxiosInstance = axios.create({
baseURL: CONFIG.messagingServiceUrl
});
messagingAxiosInstance.interceptors.response.use(
(response) => response,
(error) => Promise.reject((error.response && error.response.data) || 'Something went wrong!')
);
export default messagingAxiosInstance;
Fetcher Utility
export const fetcher = async (args) => {
try {
const [url, config] = Array.isArray(args) ? args : [args];
const res = await messagingAxiosInstance.get(url, { ...config });
return res.data;
} catch (error) {
console.error('Failed to fetch:', error);
throw error;
}
};
Service Endpoints
export const messagingEndpoints = {
messagingMessage: {
listMessagingMessages: '/v1/messagingmessages'
,
createMessagingMessage: '/v1/messagingmessages'
,
updateMessagingMessage: '/v1/messagingmessages/:messagingMessageId'
,
getMessagingMessage: '/v1/messagingmessages/:messagingMessageId'
,
deleteMessagingMessage: '/v1/messagingmessages/:messagingMessageId'
}
};
NotificationManagement Axios Configuration
import axios from 'axios';
import { CONFIG } from 'src/global-config';
const notificationManagementAxiosInstance = axios.create({
baseURL: CONFIG.notificationManagementServiceUrl
});
notificationManagementAxiosInstance.interceptors.response.use(
(response) => response,
(error) => Promise.reject((error.response && error.response.data) || 'Something went wrong!')
);
export default notificationManagementAxiosInstance;
Fetcher Utility
export const fetcher = async (args) => {
try {
const [url, config] = Array.isArray(args) ? args : [args];
const res = await notificationManagementAxiosInstance.get(url, { ...config });
return res.data;
} catch (error) {
console.error('Failed to fetch:', error);
throw error;
}
};
Service Endpoints
export const notificationManagementEndpoints = {
notification: {
createNotification: '/v1/notifications'
,
updateNotification: '/v1/notifications/:notificationId'
,
listNotifications: '/v1/notifications'
,
deleteNotification: '/v1/notifications/:notificationId'
,
getNotification: '/v1/notifications/:notificationId'
}
};
SearchIndexing Axios Configuration
import axios from 'axios';
import { CONFIG } from 'src/global-config';
const searchIndexingAxiosInstance = axios.create({
baseURL: CONFIG.searchIndexingServiceUrl
});
searchIndexingAxiosInstance.interceptors.response.use(
(response) => response,
(error) => Promise.reject((error.response && error.response.data) || 'Something went wrong!')
);
export default searchIndexingAxiosInstance;
Fetcher Utility
export const fetcher = async (args) => {
try {
const [url, config] = Array.isArray(args) ? args : [args];
const res = await searchIndexingAxiosInstance.get(url, { ...config });
return res.data;
} catch (error) {
console.error('Failed to fetch:', error);
throw error;
}
};
Service Endpoints
export const searchIndexingEndpoints = {
searchIndex: {
listSearchIndexes: '/v1/searchindexes'
,
updateSearchIndex: '/v1/searchindexs/:searchIndexId'
,
deleteSearchIndex: '/v1/searchindexs/:searchIndexId'
,
createSearchIndex: '/v1/searchindexs'
,
getSearchIndex: '/v1/searchindexs/:searchIndexId'
}
};
AdminModeration Axios Configuration
import axios from 'axios';
import { CONFIG } from 'src/global-config';
const adminModerationAxiosInstance = axios.create({
baseURL: CONFIG.adminModerationServiceUrl
});
adminModerationAxiosInstance.interceptors.response.use(
(response) => response,
(error) => Promise.reject((error.response && error.response.data) || 'Something went wrong!')
);
export default adminModerationAxiosInstance;
Fetcher Utility
export const fetcher = async (args) => {
try {
const [url, config] = Array.isArray(args) ? args : [args];
const res = await adminModerationAxiosInstance.get(url, { ...config });
return res.data;
} catch (error) {
console.error('Failed to fetch:', error);
throw error;
}
};
Service Endpoints
export const adminModerationEndpoints = {
moderationAction: {
getModerationAction: '/v1/moderationactions/:moderationActionId'
,
deleteModerationAction: '/v1/moderationactions/:moderationActionId'
,
createModerationAction: '/v1/moderationactions'
,
listModerationActions: '/v1/moderationactions'
,
updateModerationAction: '/v1/moderationactions/:moderationActionId'
}
};
WatchlistCart Axios Configuration
import axios from 'axios';
import { CONFIG } from 'src/global-config';
const watchlistCartAxiosInstance = axios.create({
baseURL: CONFIG.watchlistCartServiceUrl
});
watchlistCartAxiosInstance.interceptors.response.use(
(response) => response,
(error) => Promise.reject((error.response && error.response.data) || 'Something went wrong!')
);
export default watchlistCartAxiosInstance;
Fetcher Utility
export const fetcher = async (args) => {
try {
const [url, config] = Array.isArray(args) ? args : [args];
const res = await watchlistCartAxiosInstance.get(url, { ...config });
return res.data;
} catch (error) {
console.error('Failed to fetch:', error);
throw error;
}
};
Service Endpoints
export const watchlistCartEndpoints = {
watchlistItem: {
createWatchlistItem: '/v1/watchlistitems'
,
listWatchlistItems: '/v1/watchlistitems'
,
deleteWatchlistItem: '/v1/watchlistitems/:watchlistItemId'
},
cartItem: {
listCartItems: '/v1/cartitems'
,
deleteCartItem: '/v1/cartitems/:cartItemId'
,
updateCartItemQuantity: '/v1/cartitemquantity/:cartItemId'
,
createCartItem: '/v1/cartitems'
},
watchlistList: {
createWatchlistList: '/v1/watchlistlists'
,
deleteWatchlistList: '/v1/watchlistlists/:watchlistListId'
}
};
ProductListing Axios Configuration
import axios from 'axios';
import { CONFIG } from 'src/global-config';
const productListingAxiosInstance = axios.create({
baseURL: CONFIG.productListingServiceUrl
});
productListingAxiosInstance.interceptors.response.use(
(response) => response,
(error) => Promise.reject((error.response && error.response.data) || 'Something went wrong!')
);
export default productListingAxiosInstance;
Fetcher Utility
export const fetcher = async (args) => {
try {
const [url, config] = Array.isArray(args) ? args : [args];
const res = await productListingAxiosInstance.get(url, { ...config });
return res.data;
} catch (error) {
console.error('Failed to fetch:', error);
throw error;
}
};
Service Endpoints
export const productListingEndpoints = {
productListingMedia: {
listProductListingMedia: '/v1/productlistingmedias'
,
getProductListingMedia: '/v1/productlistingmedias/:productListingMediaId'
,
deleteProductListingMedia: '/v1/productlistingmedias/:productListingMediaId'
,
createProductListingMedia: '/v1/productlistingmedias'
},
productListingProduct: {
getProductListingProduct: '/v1/productlistingproducts/:productListingProductId'
,
listProductListingProducts: '/v1/productlistingproducts'
,
deleteProductListingProduct: '/v1/productlistingproducts/:productListingProductId'
,
updateProductListingProduct: '/v1/productlistingproducts/:productListingProductId'
,
createProductListingProduct: '/v1/productlistingproducts'
}
};
OrderManagement Axios Configuration
import axios from 'axios';
import { CONFIG } from 'src/global-config';
const orderManagementAxiosInstance = axios.create({
baseURL: CONFIG.orderManagementServiceUrl
});
orderManagementAxiosInstance.interceptors.response.use(
(response) => response,
(error) => Promise.reject((error.response && error.response.data) || 'Something went wrong!')
);
export default orderManagementAxiosInstance;
Fetcher Utility
export const fetcher = async (args) => {
try {
const [url, config] = Array.isArray(args) ? args : [args];
const res = await orderManagementAxiosInstance.get(url, { ...config });
return res.data;
} catch (error) {
console.error('Failed to fetch:', error);
throw error;
}
};
Service Endpoints
export const orderManagementEndpoints = {
orderManagementOrder: {
listOrderManagementOrders: '/v1/ordermanagementorders'
,
deleteOrderManagementOrder: '/v1/ordermanagementorders/:orderManagementOrderId'
,
getOrderManagementOrder: '/v1/ordermanagementorders/:orderManagementOrderId'
,
updateOrderManagementOrderStatus: '/v1/ordermanagementorderstatus/:orderManagementOrderId'
,
completeOrderStripeWebhook: '/v1/completeorderstripewebhook/:orderManagementOrderId'
,
createOrderManagementOrder: '/v1/ordermanagementorders'
,
startOrderManagementOrderPayment: '/v1/startordermanagementorderpayment/:orderManagementOrderId'
,
refreshOrderManagementOrderPayment: '/v1/refreshordermanagementorderpayment/:orderManagementOrderId'
,
callbackOrderManagementOrderPayment: '/v1/callbackordermanagementorderpayment'
},
orderManagementOrderItem: {
getOrderManagementOrderItem: '/v1/ordermanagementorderitems/:orderManagementOrderItemId'
,
listOrderManagementOrderItems: '/v1/ordermanagementorderitems'
},
sys_orderManagementOrderPayment: {
getOrderManagementOrderPayment2: '/v1/ordermanagementorderpayment2/:sys_orderManagementOrderPaymentId'
,
listOrderManagementOrderPayments2: '/v1/ordermanagementorderpayments2'
,
createOrderManagementOrderPayment: '/v1/ordermanagementorderpayment'
,
updateOrderManagementOrderPayment: '/v1/ordermanagementorderpayment/:sys_orderManagementOrderPaymentId'
,
deleteOrderManagementOrderPayment: '/v1/ordermanagementorderpayment/:sys_orderManagementOrderPaymentId'
,
listOrderManagementOrderPayments2: '/v1/ordermanagementorderpayments2'
,
getOrderManagementOrderPaymentByOrderId: '/v1/orderManagementOrderpaymentbyorderid/:orderId'
,
getOrderManagementOrderPaymentByPaymentId: '/v1/orderManagementOrderpaymentbypaymentid/:paymentId'
,
getOrderManagementOrderPayment2: '/v1/ordermanagementorderpayment2/:sys_orderManagementOrderPaymentId'
},
sys_paymentCustomer: {
getPaymentCustomerByUserId: '/v1/paymentcustomers/:userId'
,
listPaymentCustomers: '/v1/paymentcustomers'
},
sys_paymentMethod: {
listPaymentCustomerMethods: '/v1/paymentcustomermethods/:userId'
}
};
Feedback Axios Configuration
import axios from 'axios';
import { CONFIG } from 'src/global-config';
const feedbackAxiosInstance = axios.create({
baseURL: CONFIG.feedbackServiceUrl
});
feedbackAxiosInstance.interceptors.response.use(
(response) => response,
(error) => Promise.reject((error.response && error.response.data) || 'Something went wrong!')
);
export default feedbackAxiosInstance;
Fetcher Utility
export const fetcher = async (args) => {
try {
const [url, config] = Array.isArray(args) ? args : [args];
const res = await feedbackAxiosInstance.get(url, { ...config });
return res.data;
} catch (error) {
console.error('Failed to fetch:', error);
throw error;
}
};
Service Endpoints
export const feedbackEndpoints = {
feedback: {
listFeedbacks: '/v1/feedbacks'
,
getFeedback: '/v1/feedbacks/:feedbackId'
,
updateFeedback: '/v1/feedbacks/:feedbackId'
,
deleteFeedback: '/v1/feedbacks/:feedbackId'
,
createFeedback: '/v1/feedbacks'
}
};
Auth Axios Configuration
import axios from 'axios';
import { CONFIG } from 'src/global-config';
const authAxiosInstance = axios.create({
baseURL: CONFIG.authServiceUrl
});
authAxiosInstance.interceptors.response.use(
(response) => response,
(error) => Promise.reject((error.response && error.response.data) || 'Something went wrong!')
);
export default authAxiosInstance;
Fetcher Utility
export const fetcher = async (args) => {
try {
const [url, config] = Array.isArray(args) ? args : [args];
const res = await authAxiosInstance.get(url, { ...config });
return res.data;
} catch (error) {
console.error('Failed to fetch:', error);
throw error;
}
};
Service Endpoints
export const authEndpoints = {
login: "/login",
me: "/v1/users/:userId",
logout: "/logout",
user: {
getUser: '/v1/users/:userId'
,
updateUser: '/v1/users/:userId'
,
updateProfile: '/v1/profile/:userId'
,
createUser: '/v1/users'
,
deleteUser: '/v1/users/:userId'
,
archiveProfile: '/v1/archiveprofile/:userId'
,
listUsers: '/v1/users'
,
searchUsers: '/v1/searchusers'
,
updateUserRole: '/v1/userrole/:userId'
,
updateUserPassword: '/v1/userpassword/:userId'
,
updateUserPasswordByAdmin: '/v1/userpasswordbyadmin/:userId'
,
getBriefUser: '/v1/briefuser/:userId'
,
registerUser: '/v1/registeruser'
}
};
Service Integration
AuctionOffer Service Integration
The AuctionOffer service is integrated using:
- Service-specific Axios instance with base URL configuration
- Dynamic endpoint generation based on business logic
- Error handling through response interceptors
- Fetcher utility for data retrieval
Available Endpoints:
-
AuctionOfferOfferdata object management -
AuctionOfferBiddata object management
CategoryManagement Service Integration
The CategoryManagement service is integrated using:
- Service-specific Axios instance with base URL configuration
- Dynamic endpoint generation based on business logic
- Error handling through response interceptors
- Fetcher utility for data retrieval
Available Endpoints:
-
Categorydata object management -
Subcategorydata object management
Messaging Service Integration
The Messaging service is integrated using:
- Service-specific Axios instance with base URL configuration
- Dynamic endpoint generation based on business logic
- Error handling through response interceptors
- Fetcher utility for data retrieval
Available Endpoints:
-
MessagingMessagedata object management
NotificationManagement Service Integration
The NotificationManagement service is integrated using:
- Service-specific Axios instance with base URL configuration
- Dynamic endpoint generation based on business logic
- Error handling through response interceptors
- Fetcher utility for data retrieval
Available Endpoints:
-
Notificationdata object management
SearchIndexing Service Integration
The SearchIndexing service is integrated using:
- Service-specific Axios instance with base URL configuration
- Dynamic endpoint generation based on business logic
- Error handling through response interceptors
- Fetcher utility for data retrieval
Available Endpoints:
-
SearchIndexdata object management
AdminModeration Service Integration
The AdminModeration service is integrated using:
- Service-specific Axios instance with base URL configuration
- Dynamic endpoint generation based on business logic
- Error handling through response interceptors
- Fetcher utility for data retrieval
Available Endpoints:
-
ModerationActiondata object management
WatchlistCart Service Integration
The WatchlistCart service is integrated using:
- Service-specific Axios instance with base URL configuration
- Dynamic endpoint generation based on business logic
- Error handling through response interceptors
- Fetcher utility for data retrieval
Available Endpoints:
-
WatchlistItemdata object management -
CartItemdata object management -
WatchlistListdata object management
ProductListing Service Integration
The ProductListing service is integrated using:
- Service-specific Axios instance with base URL configuration
- Dynamic endpoint generation based on business logic
- Error handling through response interceptors
- Fetcher utility for data retrieval
Available Endpoints:
-
ProductListingMediadata object management -
ProductListingProductdata object management
OrderManagement Service Integration
The OrderManagement service is integrated using:
- Service-specific Axios instance with base URL configuration
- Dynamic endpoint generation based on business logic
- Error handling through response interceptors
- Fetcher utility for data retrieval
Available Endpoints:
-
OrderManagementOrderdata object management -
OrderManagementOrderItemdata object management -
Sys_orderManagementOrderPaymentdata object management -
Sys_paymentCustomerdata object management -
Sys_paymentMethoddata object management
Feedback Service Integration
The Feedback service is integrated using:
- Service-specific Axios instance with base URL configuration
- Dynamic endpoint generation based on business logic
- Error handling through response interceptors
- Fetcher utility for data retrieval
Available Endpoints:
-
Feedbackdata object management
Auth Service Integration
The Auth service is integrated using:
- Service-specific Axios instance with base URL configuration
- Dynamic endpoint generation based on business logic
- Error handling through response interceptors
- Fetcher utility for data retrieval
Available Endpoints:
-
Userdata object management
Request/Response Patterns
Standard Request Format
Request Structure
// Simple GET request
const response = await fetcher('/endpoint');
// GET request with parameters
const response = await fetcher(['/endpoint', { params: { id: 1 } }]);
// POST request
const response = await auctionOfferAxiosInstance.post('/endpoint', data);
// Simple GET request
const response = await fetcher('/endpoint');
// GET request with parameters
const response = await fetcher(['/endpoint', { params: { id: 1 } }]);
// POST request
const response = await categoryManagementAxiosInstance.post('/endpoint', data);
// Simple GET request
const response = await fetcher('/endpoint');
// GET request with parameters
const response = await fetcher(['/endpoint', { params: { id: 1 } }]);
// POST request
const response = await messagingAxiosInstance.post('/endpoint', data);
// Simple GET request
const response = await fetcher('/endpoint');
// GET request with parameters
const response = await fetcher(['/endpoint', { params: { id: 1 } }]);
// POST request
const response = await notificationManagementAxiosInstance.post('/endpoint', data);
// Simple GET request
const response = await fetcher('/endpoint');
// GET request with parameters
const response = await fetcher(['/endpoint', { params: { id: 1 } }]);
// POST request
const response = await searchIndexingAxiosInstance.post('/endpoint', data);
// Simple GET request
const response = await fetcher('/endpoint');
// GET request with parameters
const response = await fetcher(['/endpoint', { params: { id: 1 } }]);
// POST request
const response = await adminModerationAxiosInstance.post('/endpoint', data);
// Simple GET request
const response = await fetcher('/endpoint');
// GET request with parameters
const response = await fetcher(['/endpoint', { params: { id: 1 } }]);
// POST request
const response = await watchlistCartAxiosInstance.post('/endpoint', data);
// Simple GET request
const response = await fetcher('/endpoint');
// GET request with parameters
const response = await fetcher(['/endpoint', { params: { id: 1 } }]);
// POST request
const response = await productListingAxiosInstance.post('/endpoint', data);
// Simple GET request
const response = await fetcher('/endpoint');
// GET request with parameters
const response = await fetcher(['/endpoint', { params: { id: 1 } }]);
// POST request
const response = await orderManagementAxiosInstance.post('/endpoint', data);
// Simple GET request
const response = await fetcher('/endpoint');
// GET request with parameters
const response = await fetcher(['/endpoint', { params: { id: 1 } }]);
// POST request
const response = await feedbackAxiosInstance.post('/endpoint', data);
// Simple GET request
const response = await fetcher('/endpoint');
// GET request with parameters
const response = await fetcher(['/endpoint', { params: { id: 1 } }]);
// POST request
const response = await authAxiosInstance.post('/endpoint', data);
Response Handling
Standard Response Format
// Success response
const response = await fetcher('/endpoint');
// response contains the data directly
// Error handling
try {
const response = await fetcher('/endpoint');
} catch (error) {
console.error('API Error:', error);
// Error is already processed by the interceptor
}
Pagination Handling
Pagination Implementation
// Pagination is handled by the data grid component
// The MUI DataGrid handles pagination automatically
Error Handling Patterns
Error Classification
Error Types
// Basic error handling through Axios interceptors
// Errors are processed and simplified before reaching components
Error Handler
Centralized Error Handling
class APIErrorHandler {
handleError(error) {
if (error.response) {
// Server responded with error status
return this.handleServerError(error);
} else if (error.request) {
// Network error
return this.handleNetworkError(error);
} else {
// Other error
return this.handleUnknownError(error);
}
}
handleServerError(error) {
const { status, data } = error.response;
switch (status) {
case 400:
return new ValidationError(
data.message || 'Validation failed',
data.errors || []
);
case 401:
return new AuthenticationError(
data.message || 'Authentication required'
);
case 403:
return new AuthorizationError(
data.message || 'Access denied'
);
case 404:
return new APIError(
data.message || 'Resource not found',
404,
'NOT_FOUND'
);
case 429:
return new APIError(
data.message || 'Rate limit exceeded',
429,
'RATE_LIMIT'
);
case 500:
return new APIError(
data.message || 'Internal server error',
500,
'SERVER_ERROR'
);
default:
return new APIError(
data.message || 'Unknown server error',
status,
'UNKNOWN_ERROR'
);
}
}
handleNetworkError(error) {
return new NetworkError(
'Network error occurred',
error
);
}
handleUnknownError(error) {
return new APIError(
error.message || 'Unknown error occurred',
0,
'UNKNOWN_ERROR'
);
}
}
Retry Mechanisms
Exponential Backoff Retry
class RetryManager {
constructor(options = {}) {
this.maxRetries = options.maxRetries || 3;
this.baseDelay = options.baseDelay || 1000;
this.maxDelay = options.maxDelay || 10000;
this.retryableStatusCodes = options.retryableStatusCodes || [408, 429, 500, 502, 503, 504];
}
async executeWithRetry(operation, context = {}) {
let lastError;
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error;
if (attempt === this.maxRetries || !this.shouldRetry(error)) {
break;
}
const delay = this.calculateDelay(attempt);
await this.sleep(delay);
}
}
throw lastError;
}
shouldRetry(error) {
return false;
}
calculateDelay(attempt) {
return 0;
}
sleep(ms) {
return Promise.resolve();
}
}
Performance Optimization
Request Batching
Batch Request Manager
class BatchRequestManager {
constructor(apiClient) {
this.apiClient = apiClient;
this.pendingRequests = new Map();
this.batchTimeout = 100; // 100ms
}
async batchRequest(endpoint, data, options = {}) {
const batchKey = this.generateBatchKey(endpoint, options);
if (!this.pendingRequests.has(batchKey)) {
this.pendingRequests.set(batchKey, []);
}
const request = {
data: data,
resolve: null,
reject: null,
timestamp: Date.now()
};
const promise = new Promise((resolve, reject) => {
request.resolve = resolve;
request.reject = reject;
});
this.pendingRequests.get(batchKey).push(request);
// Process batch after timeout
setTimeout(() => this.processBatch(batchKey), this.batchTimeout);
return promise;
}
async processBatch(batchKey) {
const requests = this.pendingRequests.get(batchKey);
if (!requests || requests.length === 0) return;
this.pendingRequests.delete(batchKey);
try {
const [serviceName, endpoint] = batchKey.split(':');
const batchData = requests.map(req => req.data);
const response = await this.apiClient.post(`/${endpoint}/batch`, {
requests: batchData
});
requests.forEach((request, index) => {
if (response.data.results[index].success) {
request.resolve(response.data.results[index].data);
} else {
request.reject(new Error(response.data.results[index].error));
}
});
} catch (error) {
requests.forEach(request => {
request.reject(error);
});
}
}
}