2023年9月25日 星期一

url retry

 需求是某些地區只能打domain,有些地區只能打ip,所以pm要求我寫一個retry的功能,當一個不通在打另外一個

export const orderPostRetryHandler = async (callApi) => {
return retryHandler(callApi, [
{ baseUrl: "url1", maxTimes: 2 },
{ baseUrl: "url2", maxTimes: 2 },
])
}

export const retryHandler = (callApi, retrySettings) => {
let tryTimes = 1
let index = 0
const tryFunc = async () => {
const { baseUrl, maxTimes } = retrySettings[index]
try {
const res = await callApi(baseUrl)
if (res.status == -1) {
throw res
}
return res
} catch (e) {
tryTimes++
if (tryTimes > maxTimes) {
if (++index >= retrySettings.length) {
throw e
}
tryTimes = 1
}
return tryFunc()
}
}
return tryFunc()
}

但這有個問題,就是等打了兩遍都打不通時間都過去十秒了,真的有人願意等這麼久嗎?所以我突發奇想,為什麼不兩個網址都打,哪個通就走哪個,所以我又改成以下

export const urlChecker = (urls) => {
let passUrl = ""
return async () => {
if (passUrl) return passUrl
const res = await Promise.any(urls.map((url) => fetch(url)))
passUrl = res.url
return passUrl
}
}
const getActivatedUrl = await urlChecker("url1", "url2")
fetch(`${await getActivatedUrl()}/api/`)

這樣體驗好多了

1/19調整一下,如果使用any回來的是無效網址那就會壞掉
所以須改用Promise.all(urls.map(url => axios.get(url, {timeout: 3000})).then(urls => urls.filter(x =>x)[0])



沒有留言:

張貼留言