File size: 19,216 Bytes
8b7b267 ca2386d 8b7b267 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 |
/**
* Enhanced Crypto API Hub - Seamless Backend Integration
* Features:
* - Real backend data fetching with self-healing
* - Automatic retry and fallback mechanisms
* - Smooth error handling
* - Live API testing with CORS proxy
* - Export functionality
*/
import { showToast } from '../shared/js/components/toast-helper.js';
import { showLoading, hideLoading } from '../shared/js/components/loading-helper.js';
class CryptoAPIHub {
constructor() {
this.services = null;
this.currentFilter = 'all';
this.searchQuery = '';
this.retryCount = 0;
this.maxRetries = 3;
this.fallbackData = this.getFallbackData();
this.corsProxyEnabled = true;
}
/**
* Initialize the hub
*/
async init() {
console.log('[CryptoAPIHub] Initializing...');
// Show loading state
this.renderLoadingState();
// Fetch services data with self-healing
await this.fetchServicesWithHealing();
// Render services
this.renderServices();
// Setup event listeners
this.setupEventListeners();
// Update statistics
this.updateStats();
console.log('[CryptoAPIHub] Initialized successfully');
}
/**
* Fetch services with self-healing mechanism
*/
async fetchServicesWithHealing() {
try {
console.log('[CryptoAPIHub] Fetching services from backend...');
// Try to fetch from backend
const response = await this.fetchFromBackend();
if (response && response.categories) {
this.services = response;
this.retryCount = 0;
showToast('✅', 'Services loaded successfully', 'success');
return;
}
} catch (error) {
console.warn('[CryptoAPIHub] Backend fetch failed:', error);
}
// Self-healing: Try fallback
await this.healWithFallback();
}
/**
* Fetch from backend
*/
async fetchFromBackend() {
try {
// Try the crypto-hub API endpoint
const response = await fetch('/api/crypto-hub/services', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (response.ok) {
return await response.json();
}
throw new Error(`HTTP ${response.status}`);
} catch (error) {
console.error('[CryptoAPIHub] Backend error:', error);
throw error;
}
}
/**
* Self-healing with fallback data
*/
async healWithFallback() {
console.log('[CryptoAPIHub] Activating self-healing mechanism...');
if (this.retryCount < this.maxRetries) {
this.retryCount++;
showToast('🔄', `Retrying... (${this.retryCount}/${this.maxRetries})`, 'info');
// Wait before retry
await this.sleep(2000 * this.retryCount);
// Try again
await this.fetchServicesWithHealing();
return;
}
// All retries failed, use fallback data
console.log('[CryptoAPIHub] Using fallback data...');
this.services = this.fallbackData;
showToast('⚠️', 'Using cached data (backend unavailable)', 'warning');
}
/**
* Get fallback data (embedded for self-healing)
*/
getFallbackData() {
return {
metadata: {
version: "1.0.0",
total_services: 74,
total_endpoints: 150,
api_keys_count: 10,
last_updated: new Date().toISOString()
},
categories: {
explorer: {
name: "Blockchain Explorers",
description: "Track transactions and addresses",
services: [
{
name: "Etherscan",
url: "https://api.etherscan.io/api",
key: "SZHYFZK2RR8H9TIMJBVW54V4H81K2Z2KR2",
endpoints: [
"?module=account&action=balance&address={address}&apikey={KEY}",
"?module=gastracker&action=gasoracle&apikey={KEY}"
]
},
{
name: "BscScan",
url: "https://api.bscscan.com/api",
key: "K62RKHGXTDCG53RU4MCG6XABIMJKTN19IT",
endpoints: ["?module=account&action=balance&address={address}&apikey={KEY}"]
},
{
name: "TronScan",
url: "https://apilist.tronscanapi.com/api",
key: "7ae72726-bffe-4e74-9c33-97b761eeea21",
endpoints: ["/account?address={address}"]
}
]
},
market: {
name: "Market Data",
description: "Real-time prices and market metrics",
services: [
{
name: "CoinGecko",
url: "https://api.coingecko.com/api/v3",
key: "",
endpoints: [
"/simple/price?ids=bitcoin,ethereum&vs_currencies=usd",
"/coins/markets?vs_currency=usd&per_page=100"
]
},
{
name: "CoinMarketCap",
url: "https://pro-api.coinmarketcap.com/v1",
key: "04cf4b5b-9868-465c-8ba0-9f2e78c92eb1",
endpoints: ["/cryptocurrency/quotes/latest?symbol=BTC&convert=USD"]
},
{
name: "Binance",
url: "https://api.binance.com/api/v3",
key: "",
endpoints: ["/ticker/price?symbol=BTCUSDT"]
}
]
},
news: {
name: "News & Media",
description: "Crypto news and updates",
services: [
{
name: "CryptoPanic",
url: "https://cryptopanic.com/api/v1",
key: "",
endpoints: ["/posts/?auth_token={KEY}"]
},
{
name: "NewsAPI",
url: "https://newsapi.org/v2",
key: "pub_346789abc123def456789ghi012345jkl",
endpoints: ["/everything?q=crypto&apiKey={KEY}"]
}
]
},
sentiment: {
name: "Sentiment Analysis",
description: "Market sentiment indicators",
services: [
{
name: "Fear & Greed",
url: "https://api.alternative.me/fng/",
key: "",
endpoints: ["?limit=1", "?limit=30"]
},
{
name: "LunarCrush",
url: "https://api.lunarcrush.com/v2",
key: "",
endpoints: ["?data=assets&key={KEY}"]
}
]
},
analytics: {
name: "Analytics & Tools",
description: "Advanced analytics and whale tracking",
services: [
{
name: "Whale Alert",
url: "https://api.whale-alert.io/v1",
key: "",
endpoints: ["/transactions?api_key={KEY}&min_value=1000000"]
},
{
name: "Glassnode",
url: "https://api.glassnode.com/v1",
key: "",
endpoints: []
},
{
name: "Hugging Face",
url: "https://api-inference.huggingface.co/models",
key: "",
endpoints: ["/ElKulako/cryptobert"]
}
]
}
}
};
}
/**
* Render services grid
*/
renderServices() {
const grid = document.getElementById('servicesGrid');
if (!grid) return;
let html = '';
let count = 0;
const categories = this.services?.categories || {};
Object.entries(categories).forEach(([categoryKey, category]) => {
const services = category.services || [];
services.forEach((service, index) => {
// Apply filter
if (this.currentFilter !== 'all' && categoryKey !== this.currentFilter) {
return;
}
// Apply search
if (this.searchQuery) {
const searchLower = this.searchQuery.toLowerCase();
const matchesSearch =
service.name.toLowerCase().includes(searchLower) ||
service.url.toLowerCase().includes(searchLower) ||
categoryKey.toLowerCase().includes(searchLower);
if (!matchesSearch) return;
}
count++;
const hasKey = service.key ? `<span class="badge badge-key">🔑 Has Key</span>` : '';
const endpoints = service.endpoints?.length || 0;
html += `
<div class="service-card" data-category="${categoryKey}" data-name="${service.name.toLowerCase()}" style="animation-delay: ${index * 0.05}s">
<div class="service-header">
<div class="service-icon">${this.getIcon(categoryKey)}</div>
<div class="service-info">
<div class="service-name">${service.name}</div>
<div class="service-url">${service.url}</div>
</div>
</div>
<div class="service-badges">
<span class="badge badge-category">${categoryKey}</span>
${endpoints > 0 ? `<span class="badge badge-endpoints">${endpoints} endpoints</span>` : ''}
${hasKey}
</div>
${this.renderEndpoints(service, categoryKey)}
</div>
`;
});
});
if (html === '') {
html = '<div class="empty-state"><div class="empty-icon">🔍</div><div class="empty-text">No services found</div></div>';
}
grid.innerHTML = html;
}
/**
* Render endpoints for a service
*/
renderEndpoints(service, category) {
const endpoints = service.endpoints || [];
if (endpoints.length === 0) {
return '<div class="no-endpoints">Base endpoint available</div>';
}
let html = '<div class="endpoints-list">';
endpoints.slice(0, 2).forEach(endpoint => {
const fullUrl = service.url + endpoint;
const encodedUrl = encodeURIComponent(fullUrl);
html += `
<div class="endpoint-item">
<div class="endpoint-path">${endpoint}</div>
<div class="endpoint-actions">
<button class="btn-sm" onclick="window.cryptoAPIHub.copyText('${fullUrl.replace(/'/g, "\\'")}')">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
</svg>
Copy
</button>
<button class="btn-sm" onclick="window.cryptoAPIHub.testEndpoint('${fullUrl.replace(/'/g, "\\'")}', '${service.key || ''}')">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline>
</svg>
Test
</button>
</div>
</div>
`;
});
if (endpoints.length > 2) {
html += `<div class="more-endpoints">+${endpoints.length - 2} more endpoints</div>`;
}
html += '</div>';
return html;
}
/**
* Get icon for category
*/
getIcon(category) {
const icons = {
explorer: '<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg>',
market: '<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><line x1="12" y1="20" x2="12" y2="10"></line><line x1="18" y1="20" x2="18" y2="4"></line><line x1="6" y1="20" x2="6" y2="16"></line></svg>',
news: '<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2"></path><path d="M18 14h-8"></path><path d="M15 18h-5"></path><path d="M10 6h8v4h-8V6Z"></path></svg>',
sentiment: '<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 1.98-3A2.5 2.5 0 0 1 9.5 2Z"></path><path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-1.98-3A2.5 2.5 0 0 0 14.5 2Z"></path></svg>',
analytics: '<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><path d="M3 3v18h18"></path><path d="m19 9-5 5-4-4-3 3"></path></svg>'
};
return icons[category] || icons.analytics;
}
/**
* Render loading state
*/
renderLoadingState() {
const grid = document.getElementById('servicesGrid');
if (!grid) return;
grid.innerHTML = `
<div class="loading-state">
<div class="loading-spinner"></div>
<div class="loading-text">Loading services...</div>
</div>
`;
}
/**
* Update statistics
*/
updateStats() {
const metadata = this.services?.metadata || {};
const statsData = {
services: metadata.total_services || 74,
endpoints: metadata.total_endpoints || 150,
keys: metadata.api_keys_count || 10
};
// Update stat values
document.querySelectorAll('.stat-value').forEach((el, index) => {
const values = [statsData.services, statsData.endpoints + '+', statsData.keys];
if (el && values[index]) {
el.textContent = values[index];
}
});
}
/**
* Setup event listeners
*/
setupEventListeners() {
// Search input
const searchInput = document.getElementById('searchInput');
if (searchInput) {
searchInput.addEventListener('input', (e) => {
this.searchQuery = e.target.value;
this.renderServices();
});
}
// Filter tabs
document.querySelectorAll('.filter-tab').forEach(tab => {
tab.addEventListener('click', (e) => {
this.setFilter(e.target.dataset.filter);
});
});
// Method buttons
document.querySelectorAll('.method-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const method = e.target.dataset.method;
this.setMethod(method);
});
});
// Update last update time
this.updateLastUpdateTime();
}
/**
* Set HTTP method
*/
setMethod(method) {
this.currentMethod = method;
// Update active button
document.querySelectorAll('.method-btn').forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.method === method) {
btn.classList.add('active');
}
});
// Show/hide body field
const bodyGroup = document.getElementById('bodyGroup');
if (bodyGroup) {
bodyGroup.style.display = (method === 'POST' || method === 'PUT') ? 'block' : 'none';
}
}
/**
* Update last update time
*/
updateLastUpdateTime() {
const el = document.getElementById('lastUpdate');
if (el) {
el.textContent = `Last updated: ${new Date().toLocaleTimeString()}`;
}
}
/**
* Set filter
*/
setFilter(filter) {
this.currentFilter = filter;
// Update active tab
document.querySelectorAll('.filter-tab').forEach(t => t.classList.remove('active'));
const activeTab = document.querySelector(`[data-filter="${filter}"]`);
if (activeTab) activeTab.classList.add('active');
// Re-render
this.renderServices();
}
/**
* Copy text to clipboard
*/
async copyText(text) {
try {
await navigator.clipboard.writeText(text);
showToast('✅', 'Copied to clipboard!', 'success');
} catch (error) {
showToast('❌', 'Failed to copy', 'error');
}
}
/**
* Test endpoint
*/
async testEndpoint(url, key) {
// Replace key placeholders
let finalUrl = url;
if (key) {
finalUrl = url.replace('{KEY}', key).replace('{key}', key);
}
// Open tester modal with URL
this.openTester(finalUrl);
}
/**
* Open API tester modal
*/
openTester(url = '') {
const modal = document.getElementById('testerModal');
const urlInput = document.getElementById('testUrl');
if (modal) {
modal.classList.add('active');
if (urlInput && url) {
urlInput.value = url;
}
}
}
/**
* Close API tester modal
*/
closeTester() {
const modal = document.getElementById('testerModal');
if (modal) {
modal.classList.remove('active');
}
}
/**
* Send API test request
*/
async sendTestRequest() {
const url = document.getElementById('testUrl')?.value;
const headersText = document.getElementById('testHeaders')?.value || '{}';
const bodyText = document.getElementById('testBody')?.value;
const responseBox = document.getElementById('responseBox');
const responseJson = document.getElementById('responseJson');
const method = this.currentMethod || 'GET';
if (!url) {
showToast('⚠️', 'Please enter a URL', 'warning');
return;
}
if (responseBox) responseBox.style.display = 'block';
if (responseJson) responseJson.textContent = '⏳ Sending request...';
try {
// Use CORS proxy if enabled
const requestUrl = this.corsProxyEnabled
? `/api/crypto-hub/test`
: url;
const requestOptions = this.corsProxyEnabled
? {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: url,
method: method,
headers: JSON.parse(headersText),
body: bodyText
})
}
: {
method: method,
headers: JSON.parse(headersText),
body: (method === 'POST' || method === 'PUT') ? bodyText : undefined
};
const response = await fetch(requestUrl, requestOptions);
const data = await response.json();
if (responseJson) {
responseJson.textContent = JSON.stringify(data, null, 2);
}
showToast('✅', 'Request successful!', 'success');
} catch (error) {
if (responseJson) {
responseJson.textContent = `❌ Error: ${error.message}\n\nThis might be due to CORS policy. Try using the CORS proxy.`;
}
showToast('❌', 'Request failed', 'error');
}
}
/**
* Export services as JSON
*/
exportJSON() {
const data = {
metadata: {
exported_at: new Date().toISOString(),
...this.services?.metadata
},
services: this.services
};
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `crypto-api-hub-${Date.now()}.json`;
a.click();
URL.revokeObjectURL(url);
showToast('✅', 'JSON exported successfully!', 'success');
}
/**
* Sleep utility
*/
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
window.cryptoAPIHub = new CryptoAPIHub();
window.cryptoAPIHub.init();
});
// Export for module usage
export default CryptoAPIHub;
|