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