api timeout now printed in browser console
Massimo Melina committed
Sep 29, 2023 at 19:27 UTC
a5a3aab367488b6beb413f7a2fce71a3fea9eeea
1 file changed
+7
-4
shared/api.ts
+7
-4
@@ -28,8 +28,11 @@ export function apiCall<T=any>(cmd: string, params?: Dict, options: ApiCallOptio
28
const stop = options.modal?.(cmd, params)
29
const controller = new AbortController()
30
let aborted = ''
31
- if (options.timeout !== false)
32
- setTimeout(() => controller.abort(aborted='timeout'), 1000*(timeoutByApi[cmd] ?? options.timeout ?? 10))
31
+ const ms = 1000 * (timeoutByApi[cmd] ?? options.timeout ?? 10)
32
+ const timeout = ms && setTimeout(() => {
33
+ controller.abort(aborted = 'timeout')
34
+ console.debug('API TIMEOUT', cmd, params??'')
35
+ }, ms)
36
return Object.assign(fetch(getPrefixUrl() + API_URL + cmd, {
37
method: 'POST',
38
headers: { 'content-type': 'application/json', 'x-hfs-anti-csrf': '1' },
@@ -42,7 +45,7 @@ export function apiCall<T=any>(cmd: string, params?: Dict, options: ApiCallOptio
45
try { data = JSON.parse(body) }
46
catch {}
47
const result = data ?? body
45
- console.debug(res.ok ? 'API' : 'API FAILED', cmd, params, '>>', result)
48
+ console.debug(res.ok ? 'API' : 'API FAILED', cmd, params??'', '>>', result)
49
await options.onResponse?.(res, result)
50
if (!res.ok)
51
throw new ApiError(res.status, data === undefined ? body : `Failed API ${cmd}: ${res.statusText}`, data)
@@ -52,7 +55,7 @@ export function apiCall<T=any>(cmd: string, params?: Dict, options: ApiCallOptio
55
if (err?.message?.includes('fetch'))
56
throw Error("Network error")
57
throw aborted || err
55
- }), {
58
+ }).finally(() => clearTimeout(timeout)), {
59
abort() {
60
controller.abort(aborted='cancel')
61
}