(urlTemplate, maxRetriesPerKey = 3)
| 26 | } |
| 27 | |
| 28 | async fetchWithKeySwitch(urlTemplate, maxRetriesPerKey = 3) { |
| 29 | let attempts = 0; |
| 30 | const totalAttemptsLimit = this.userToken ? maxRetriesPerKey : this.keys.length * maxRetriesPerKey; |
| 31 | |
| 32 | while (attempts < totalAttemptsLimit) { |
| 33 | const url = urlTemplate(this.getCurrentKey()); |
| 34 | try { |
| 35 | const response = window.FreeMovieApi |
| 36 | ? await window.FreeMovieApi.request(url) |
| 37 | : await fetch(url); |
| 38 | if (!response.ok) { |
| 39 | if (response.status === 429) { |
| 40 | console.warn('محدودیت نرخ OMDB API - تلاش مجدد...'); |
| 41 | await new Promise(resolve => setTimeout(resolve, 1000)); |
| 42 | attempts++; |
| 43 | continue; |
| 44 | } |
| 45 | throw new Error(`خطای سرور (OMDB): ${response.status}`); |
| 46 | } |
| 47 | return await response.json(); |
| 48 | } catch (error) { |
| 49 | console.warn(`خطا در درخواست با کلید ${this.getCurrentKey()}: ${error.message}`); |
| 50 | attempts++; |
| 51 | if (!this.userToken && attempts % maxRetriesPerKey === 0) { |
| 52 | this.switchToNextKey(); |
| 53 | } |
| 54 | await new Promise(resolve => setTimeout(resolve, 1000)); |
| 55 | if (attempts >= totalAttemptsLimit) { |
| 56 | throw new Error('تمام تلاشها ناموفق بود.'); |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | async function loadApiKeys() { |
no test coverage detected