Repository navigation
Expand file tree
/
Copy pathapiKeySwitcher.js
More file actions
66 lines (61 loc) · 2.42 KB
/
Copy pathapiKeySwitcher.js
File metadata and controls
66 lines (61 loc) · 2.42 KB
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
// apiKeySwitcher.js
class ApiKeySwitcher {
constructor(keys) {
this.keys = keys || [];
this.currentIndex = 0;
}
// Get the current API key
getCurrentKey() {
if (this.keys.length === 0) {
throw new Error('هیچ کلید API در دسترس نیست.');
}
return this.keys[this.currentIndex];
}
// Switch to the next API key
switchToNextKey() {
this.currentIndex = (this.currentIndex + 1) % this.keys.length;
console.log(`تعویض به کلید API جدید: ${this.getCurrentKey()}`);
}
// Fetch with automatic key switching
async fetchWithKeySwitch(urlTemplate, maxRetries = null) {
const retries = maxRetries !== null ? maxRetries : this.keys.length;
let attempts = 0;
while (attempts < retries) {
const url = urlTemplate(this.getCurrentKey());
try {
const response = await fetch(url);
if (!response.ok) {
if (response.status === 429) {
console.warn('محدودیت نرخ OMDB API - تعویض کلید...');
this.switchToNextKey();
attempts++;
continue;
}
throw new Error(`خطای سرور (OMDB): ${response.status}`);
}
return await response.json();
} catch (error) {
console.warn(`خطا در درخواست با کلید ${this.getCurrentKey()}: ${error.message}`);
this.switchToNextKey();
attempts++;
if (attempts >= retries) {
throw new Error('تمام کلیدهای API امتحان شدند و خطا ادامه دارد.');
}
}
}
}
}
// Load API keys from JSON file
async function loadApiKeys() {
try {
const response = await fetch('./omdbKeys.json'); // فرض بر این است که omdbKeys.json در همان پوشه است
if (!response.ok) {
throw new Error(`خطا در بارگذاری فایل JSON: ${response.status}`);
}
const keys = await response.json();
return new ApiKeySwitcher(keys);
} catch (error) {
console.error('خطا در بارگذاری کلیدهای API:', error);
return new ApiKeySwitcher(['38fa39d5']); // کلید پیشفرض
}
}