-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrapperAPIcall
More file actions
66 lines (54 loc) · 1.58 KB
/
wrapperAPIcall
File metadata and controls
66 lines (54 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
export function createApiClient({
baseUrl,
refreshPath = "/refresh",
credentials = "include",
onAuthFail = null,
} = {}) {
let refreshPromise = null;
async function refreshOnce() {
if (!refreshPromise) {
refreshPromise = fetch(baseUrl + refreshPath, {
method: "POST",
credentials,
headers: { "Content-Type": "application/json" },
body: "{}",
})
.then((r) => r.ok)
.catch(() => false)
.finally(() => {
refreshPromise = null;
});
}
return refreshPromise;
}
async function request(path, { method = "GET", body = undefined, headers = {}, retry = true } = {}) {
const h = { ...headers };
const hasBody = body !== undefined && body !== null;
if (hasBody && !h["Content-Type"]) h["Content-Type"] = "application/json";
const doFetch = () =>
fetch(baseUrl + path, {
method,
credentials,
headers: h,
body: hasBody ? (h["Content-Type"] === "application/json" ? JSON.stringify(body) : body) : undefined,
});
const res1 = await doFetch();
if (res1.status !== 401 || retry === false) return res1;
const ok = await refreshOnce();
if (!ok) {
if (typeof onAuthFail === "function") onAuthFail(res1);
return res1;
}
return doFetch();
}
return { request };
}
/*
Usage:
const api = createApiClient({
baseUrl: "/authentification/backend",
onAuthFail: () => window.location.assign("/login"),
});
const r = await api.request("/me");
const r2 = await api.request("/users", { method: "POST", body: { ... } });
*/