(requestId, key, maxAttempts = 900, interval = 2000)
| 15 | } |
| 16 | |
| 17 | async function pollForResult(requestId, key, maxAttempts = 900, interval = 2000) { |
| 18 | const pollUrl = `${BASE_URL}/api/v1/predictions/${requestId}/result`; |
| 19 | for (let attempt = 1; attempt <= maxAttempts; attempt++) { |
| 20 | await new Promise(resolve => setTimeout(resolve, interval)); |
| 21 | try { |
| 22 | const response = await fetch(pollUrl, { |
| 23 | headers: { 'Content-Type': 'application/json', 'x-api-key': key } |
| 24 | }); |
| 25 | if (!response.ok) { |
| 26 | const errText = await response.text(); |
| 27 | if (response.status >= 500) continue; |
| 28 | notifyAuthRequired(response.status, errText); |
| 29 | throw new Error(`Poll Failed: ${response.status} - ${errText.slice(0, 100)}`); |
| 30 | } |
| 31 | const data = await response.json(); |
| 32 | const status = data.status?.toLowerCase(); |
| 33 | if (status === 'completed' || status === 'succeeded' || status === 'success') return data; |
| 34 | if (status === 'failed' || status === 'error') throw new Error(`Generation failed: ${data.error || 'Unknown error'}`); |
| 35 | } catch (error) { |
| 36 | if (attempt === maxAttempts) throw error; |
| 37 | } |
| 38 | } |
| 39 | throw new Error('Generation timed out after polling.'); |
| 40 | } |
| 41 | |
| 42 | async function submitAndPoll(endpoint, payload, key, onRequestId, maxAttempts = 60) { |
| 43 | const url = `${BASE_URL}/api/v1/${endpoint}`; |
no test coverage detected