2024-03-28 13:53:40 +00:00
|
|
|
import { getAtk, getRtk } from "@/stores/userinfo"
|
|
|
|
import { Preferences } from "@capacitor/preferences"
|
|
|
|
|
2024-03-27 15:07:18 +00:00
|
|
|
const serviceMap: { [id: string]: string } = {
|
|
|
|
interactive: "https://co.solsynth.dev",
|
2024-03-30 12:08:39 +00:00
|
|
|
identity: "https://id.solsynth.dev",
|
2024-04-05 05:03:29 +00:00
|
|
|
messaging: "https://im.solsynth.dev"
|
2024-03-27 15:07:18 +00:00
|
|
|
}
|
|
|
|
|
2024-03-28 13:53:40 +00:00
|
|
|
export async function request(service: string, input: string, init?: RequestInit, noRetry?: boolean) {
|
2024-03-27 15:07:18 +00:00
|
|
|
const url = buildRequestUrl(service, input)
|
2024-03-28 13:53:40 +00:00
|
|
|
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"]
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
console.info("[REQUEST] Auth context has been refreshed.")
|
2024-04-05 05:03:29 +00:00
|
|
|
return await request(service, input, {
|
|
|
|
...init,
|
|
|
|
headers: { ...init?.headers, Authorization: `Bearer ${await getAtk()}` }
|
|
|
|
}, true)
|
2024-03-28 13:53:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return res
|
2024-03-27 15:07:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function buildRequestUrl(service: string, input: string) {
|
|
|
|
const prefix = serviceMap[service] ?? ""
|
|
|
|
return prefix + input
|
|
|
|
}
|