@xbibzlibrary/connect
v1.0.2-nextgen
Published
Advanced Fetch & CORS Handler with Comprehensive Error Management
Maintainers
Readme
XbibzConnect
Advanced Fetch & CORS Handler with Comprehensive Error Management
Features • Installation • Quick Start • Documentation • Examples
🚀 Overview
XbibzConnect is a robust JavaScript library designed to eliminate the frustration of Failed to Fetch errors and CORS issues. Built with enterprise-grade reliability, it provides intelligent retry mechanisms, advanced caching strategies, and comprehensive error handling to ensure your network requests succeed even in challenging conditions.
Why XbibzConnect?
Traditional Fetch
fetch('https://api.example.com/data')
.then(response => response.json())
.catch(error => {
// 😞 Failed to fetch
// 😞 CORS error
// 😞 Network timeout
console.error('Failed:', error);
});With XbibzConnect
const connect = new XbibzConnect();
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// ✅ Automatic retry
// ✅ CORS handling
// ✅ Smart caching
console.log('Success:', data);
});✨ Features
🔄 Intelligent Retry Strategy
Automatically retries failed requests with configurable backoff strategies including exponential, linear, and random delays. No more manual retry logic needed.
🌐 Advanced CORS Handling
Seamlessly handles cross-origin requests with built-in proxy support and fallback mechanisms. Say goodbye to CORS headaches.
💾 Smart Caching System
Implements multiple caching strategies to reduce network load and improve performance. Cache responses intelligently with automatic cleanup.
📊 Performance Monitoring
Track request metrics, success rates, and response times with built-in analytics. Optimize your application with real-time insights.
🛡️ Comprehensive Error Management
Categorizes and handles errors intelligently with detailed context and recovery strategies. Know exactly what went wrong and why.
🔍 Response Validation
Validate responses against schemas, status codes, and content types automatically. Ensure data integrity before processing.
📝 Advanced Logging
Detailed logging system with multiple levels, timestamps, and persistent storage options. Debug with confidence.
⚡ Zero Dependencies
Lightweight and self-contained with no external dependencies. Just plug and play.
📦 Installation
Via CDN
<script src="https://cdn.xbibz.com/[email protected]/xbibzlibrary-connect.min.js"></script>Via NPM
npm install @xbibzlibrary/connectVia Yarn
yarn add @xbibzlibrary/connectManual Installation
git clone https://github.com/xbibzlibrary/connect.git
cd connect
bash build.sh🎯 Quick Start
Basic Usage
// Initialize with default configuration
const connect = new XbibzConnect();
// Your fetch requests now have superpowers!
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));Custom Configuration
const connect = new XbibzConnect({
retry: {
attempts: 5,
delay: 2000,
backoff: 'exponential'
},
cache: {
enabled: true,
maxAge: 600000 // 10 minutes
},
timeout: 15000,
logging: {
enabled: true,
level: 'verbose'
}
});🎨 Configuration Options
Retry Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| attempts | Number | 3 | Maximum number of retry attempts |
| delay | Number | 1000 | Initial delay between retries (ms) |
| backoff | String | 'exponential' | Backoff strategy: exponential, linear, random |
| maxDelay | Number | 30000 | Maximum delay between retries (ms) |
Cache Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| enabled | Boolean | true | Enable/disable caching |
| maxAge | Number | 300000 | Cache lifetime in milliseconds |
| strategy | String | 'network-first' | Caching strategy |
CORS Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| mode | String | 'cors' | CORS mode: cors, no-cors, same-origin |
| credentials | String | 'same-origin' | Credentials mode |
Logging Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| enabled | Boolean | true | Enable/disable logging |
| level | String | 'verbose' | Log level: error, warn, info, verbose, debug |
| timestamp | Boolean | true | Include timestamps in logs |
| persistent | Boolean | false | Store logs in localStorage |
💡 Examples
Example 1: Handling API with Retry
const connect = new XbibzConnect({
retry: {
attempts: 5,
delay: 1000,
backoff: 'exponential'
}
});
async function fetchUserData() {
try {
const response = await fetch('https://api.example.com/users/123');
const data = await response.json();
return data;
} catch (error) {
console.error('Failed after retries:', error);
}
}Example 2: CORS Proxy Fallback
const connect = new XbibzConnect({
fallback: {
enabled: true,
endpoints: [
{
original: 'https://external-api.com',
fallback: 'https://cors-proxy.example.com/https://external-api.com'
}
]
}
});
// Automatically falls back to proxy if CORS fails
fetch('https://external-api.com/data')
.then(response => response.json())
.then(data => console.log(data));Example 3: Response Validation
const connect = new XbibzConnect({
validation: {
validateResponse: true,
allowedStatuses: [200, 201],
contentTypes: ['application/json'],
schema: {
type: 'object',
required: ['id', 'name', 'email']
}
}
});
// Only valid responses pass through
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => {
// Data is guaranteed to match schema
console.log(data);
});Example 4: Performance Monitoring
const connect = new XbibzConnect();
// Make some requests
await fetch('https://api.example.com/data1');
await fetch('https://api.example.com/data2');
await fetch('https://api.example.com/data3');
// Get performance metrics
const metrics = connect.getMetrics();
console.log('Total Requests:', metrics.totalRequests);
console.log('Success Rate:',
(metrics.successfulRequests / metrics.totalRequests * 100).toFixed(2) + '%');
console.log('Average Response Time:',
metrics.averageResponseTime.toFixed(2) + 'ms');Example 5: Cache Management
const connect = new XbibzConnect({
cache: {
enabled: true,
maxAge: 300000, // 5 minutes
strategy: 'network-first'
}
});
// First request hits network
await fetch('https://api.example.com/products');
// Second request uses cache
await fetch('https://api.example.com/products'); // Instant!
// Clear cache when needed
connect.clearCache();📚 API Reference
XbibzConnect Class
Constructor
new XbibzConnect(config?: Object)Creates a new instance with optional configuration.
Methods
getMetrics()
Returns performance metrics for all requests.
const metrics = connect.getMetrics();
// {
// totalRequests: 10,
// successfulRequests: 9,
// failedRequests: 1,
// averageResponseTime: 234.56
// }clearCache()
Clears all cached responses.
const clearedCount = connect.clearCache();
console.log(`Cleared ${clearedCount} cache entries`);updateConfig(newConfig)
Updates the configuration dynamically.
connect.updateConfig({
retry: { attempts: 10 },
timeout: 20000
});static create(config)
Static factory method to create instances.
const connect = XbibzConnect.create({ timeout: 5000 });🏗️ Architecture
xbibzlibrary-connect/
├── src/
│ ├── core/
│ │ ├── ErrorHandler.js # Error categorization and handling
│ │ ├── RequestInterceptor.js # Request modification and enhancement
│ │ └── ResponseValidator.js # Response validation logic
│ ├── strategies/
│ │ ├── RetryStrategy.js # Retry logic with backoff
│ │ ├── CacheStrategy.js # Caching implementation
│ │ └── FallbackStrategy.js # Fallback endpoint handling
│ ├── utils/
│ │ ├── Logger.js # Logging system
│ │ ├── Validator.js # Input validation
│ │ └── Helpers.js # Utility functions
│ ├── config/
│ │ └── DefaultConfig.js # Default configuration
│ └── main.js # Main entry point
├── package.json
├── build.sh
└── README.md🔧 Advanced Usage
Custom Error Handlers
const connect = new XbibzConnect();
connect._errorHandler.registerCustomErrorHandler('CustomError', {
type: 'CUSTOM_ERROR',
severity: 'HIGH',
recovery: 'CUSTOM_STRATEGY'
});Request Interceptors
connect._requestInterceptor.addInterceptor((init) => {
init.headers.set('Authorization', 'Bearer TOKEN');
return init;
});Custom Validators
connect._responseValidator.addValidator('custom', async (response) => {
const data = await response.clone().json();
return {
valid: data.status === 'success',
error: data.status !== 'success' ? 'Invalid status' : null
};
});🎓 Best Practices
1. Configure Based on Your Needs
Adjust retry attempts and delays based on your API characteristics and user experience requirements.
2. Use Appropriate Cache Strategies
Enable caching for GET requests to static or semi-static data to reduce server load and improve performance.
3. Monitor Performance Metrics
Regularly check metrics to identify problematic endpoints and optimize your application.
4. Set Reasonable Timeouts
Configure timeouts based on expected response times to prevent hanging requests.
5. Implement Proper Error Handling
Always handle errors gracefully and provide meaningful feedback to users.
🤝 Contributing
Contributions are welcome! Please read our contributing guidelines before submitting pull requests.
# Fork the repository
git clone https://github.com/xbibzlibrary/connect.git
cd connect
# Create a feature branch
git checkout -b feature/amazing-feature
# Make your changes and commit
git commit -m "Add amazing feature"
# Push to your fork
git push origin feature/amazing-feature
# Open a Pull Request📄 License
This project is licensed under the MIT License. See the LICENSE file for details.
🌟 Support
Documentation
Visit our official documentation for comprehensive guides and tutorials.
Issues
Found a bug? Open an issue on GitHub.
Community
Join our Discord community for discussions and support.
Professional Support
Need enterprise support? Contact us at [email protected]
🎉 Acknowledgments
Special thanks to all contributors and the open-source community for making this project possible.
Made with ❤️ by Xbibz Official
⭐ Star us on GitHub if this project helped you!
