🐛 Fix infinite reconnect issue

This commit is contained in:
2024-04-05 21:48:53 +08:00
parent c1f42ed4f7
commit 202b6c1a10
3 changed files with 38 additions and 32 deletions

View File

@@ -7,33 +7,37 @@ const serviceMap: { [id: string]: string } = {
messaging: "https://im.solsynth.dev"
}
export async function refreshToken() {
const res = await request("identity", "/api/auth/token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
refresh_token: await getRtk(),
grant_type: "refresh_token"
})
}, true)
if (res.status !== 200) {
const err = await res.text()
throw new Error(err)
} else {
const data = await res.json()
await Preferences.set({
key: "identity.access_token",
value: data["access_token"]
})
await Preferences.set({
key: "identity.refresh_token",
value: data["refresh_token"]
})
}
}
export async function request(service: string, input: string, init?: RequestInit, noRetry?: boolean) {
const url = buildRequestUrl(service, input)
const res = await fetch(url, init)
if (res.status === 401 && !noRetry) {
const res = await request("identity", "/api/auth/token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
refresh_token: await getRtk(),
grant_type: "refresh_token"
})
}, true)
if (res.status !== 200) {
const err = await res.text()
throw new Error(err)
} else {
const data = await res.json()
await Preferences.set({
key: "identity.access_token",
value: data["access_token"]
})
await Preferences.set({
key: "identity.refresh_token",
value: data["refresh_token"]
})
}
await refreshToken()
console.info("[REQUEST] Auth context has been refreshed.")
return await request(service, input, {