-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.js
45 lines (41 loc) · 1.14 KB
/
client.js
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
export const client = (url, method = "GET", body = null) => {
return new Promise(async (resolve, reject) => {
const response1 = await customFetch(url, method, body)
if (response1.status !== 401) {
return resolve(response1)
}
const hasTokenUpdated = await requestAccessToken()
if (hasTokenUpdated) {
const response2 = await customFetch(url, method, body)
return resolve(response2)
} else {
return reject({ message: "Not authenticated", ok: false })
}
})
}
export const customFetch = async (url, method = "GET", body = null) => {
const res = await fetch(url, {
method,
body: body && JSON.stringify(body),
credentials: "include",
headers: {
Authorization: "Bearer " + localStorage.getItem("accessToken"),
"Content-Type": "application/json",
},
})
const json = await res.json()
return {
ok: res.ok,
status: res.status,
data: json.data,
message: json.message,
}
}
export const requestAccessToken = async () => {
const { ok, data: accessToken, message } = await customFetch("/api/auth/refresh_token", "POST")
console.log(message)
if (ok) {
localStorage.setItem("accessToken", accessToken)
}
return ok
}