Add retry for posting video cache from web app

This commit is contained in:
Brahim Hadriche committed 2024-09-23 12:47:42 -04:00
1 parent 9fb7f1ac0a
commit bc7f61e01b
1 file changed
+43 -9
+43 -9
View File
@@ -277,16 +277,50 @@ export class YoutubeJs {
} }
static async postCacheData(data) { static async postCacheData(data) {
await YoutubeJs.postJson(`${YoutubeJs.host()}/api/ytjs-cache`, data); const maxRetries = 2;
const timeout = 5000;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
await YoutubeJs.postJson(`${YoutubeJs.host()}/api/ytjs-cache`, data, timeout);
break;
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
console.warn(`Attempt ${attempt} failed. Retrying...`);
}
}
} }
private static postJson(url, payload) { private static postJson(url, payload, timeout) {
return fetch(url, { return new Promise((resolve, reject) => {
headers: { const controller = new AbortController();
'Content-Type': 'application/json' const timer = setTimeout(() => {
}, controller.abort();
method: "POST", reject(new Error('Request timed out'));
body: JSON.stringify(payload) }, timeout);
})
fetch(url, {
headers: {
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(payload),
signal: controller.signal
})
.then(response => {
clearTimeout(timer);
resolve(response);
})
.catch(err => {
clearTimeout(timer);
if (err.name === 'AbortError') {
reject(new Error('Request was aborted'));
} else {
reject(err);
}
});
});
} }
} }