| 1 |
import { useLaunchDataStore } from '@auto-launch/state/launch-data'; |
| 2 |
import { digest } from '@shared/api/digest'; |
| 3 |
import { __ } from '@wordpress/i18n'; |
| 4 |
|
| 5 |
export const setStatus = (msg) => { |
| 6 |
useLaunchDataStore.getState().addStatusMessage(msg); |
| 7 |
}; |
| 8 |
export const setErrorMessage = (message) => { |
| 9 |
useLaunchDataStore.getState().setErrorMessage(message); |
| 10 |
}; |
| 11 |
|
| 12 |
export const retryTwice = async (fn) => { |
| 13 |
try { |
| 14 |
return await fn(); |
| 15 |
} catch (_) { |
| 16 |
setErrorMessage( |
| 17 |
// translators: This is an error message shown to the user when a network request fails and is being retried |
| 18 |
__('The network seems unstable. Retrying...', 'extendify-local'), |
| 19 |
); |
| 20 |
await wait(1000); |
| 21 |
const res = await fn(); |
| 22 |
setErrorMessage(null); |
| 23 |
return res; |
| 24 |
} |
| 25 |
}; |
| 26 |
|
| 27 |
export const failWithFallback = async (fn, fallback, errDetails = {}) => { |
| 28 |
try { |
| 29 |
return await fn(); |
| 30 |
} catch (error) { |
| 31 |
digest({ |
| 32 |
...errDetails, |
| 33 |
error: errDetails?.error ?? error, |
| 34 |
source: 'auto-launch', |
| 35 |
}); |
| 36 |
return fallback; |
| 37 |
} |
| 38 |
}; |
| 39 |
|
| 40 |
export const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 41 |
|
| 42 |
import apiFetch from '@wordpress/api-fetch'; |
| 43 |
|
| 44 |
export async function apiFetchWithTimeout(options = {}, timeoutMs = 30000) { |
| 45 |
const controller = new AbortController(); |
| 46 |
const { signal } = controller; |
| 47 |
const timeoutId = setTimeout(() => controller.abort(), timeoutMs); |
| 48 |
|
| 49 |
try { |
| 50 |
return await apiFetch({ ...options, signal }); |
| 51 |
} finally { |
| 52 |
clearTimeout(timeoutId); |
| 53 |
} |
| 54 |
} |
| 55 |
export const fetchWithTimeout = async ( |
| 56 |
url, |
| 57 |
options = {}, |
| 58 |
timeoutMs = 60000, |
| 59 |
) => { |
| 60 |
const controller = new AbortController(); |
| 61 |
const { signal } = controller; |
| 62 |
const timeoutId = setTimeout(() => controller.abort(), timeoutMs); |
| 63 |
|
| 64 |
try { |
| 65 |
return await fetch(url, { ...options, signal }); |
| 66 |
} finally { |
| 67 |
clearTimeout(timeoutId); |
| 68 |
} |
| 69 |
}; |
| 70 |
|