Spaces:
Runtime error
Runtime error
File size: 2,323 Bytes
c5cf697 2b32e9d c5cf697 2b32e9d c5cf697 2b32e9d c5cf697 2b32e9d c5cf697 | 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | import {
clearSession,
getAccessToken,
getRefreshToken,
getStoredUser,
setSession,
} from '../auth/storage'
import { apiUrl } from '../config/apiBase'
async function readDetail(res) {
try {
const data = await res.json()
const d = data.detail
if (typeof d === 'string') return d
if (Array.isArray(d))
return d.map((e) => e.msg || JSON.stringify(e)).join(' ')
return data.message || res.statusText
} catch {
return res.statusText || 'Request failed'
}
}
async function postRefresh() {
const rt = getRefreshToken()
if (!rt) return null
const res = await fetch(apiUrl('/users/refresh'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: rt }),
})
if (!res.ok) return null
const text = await res.text()
return text ? JSON.parse(text) : null
}
function redirectToLogin() {
clearSession()
if (typeof window !== 'undefined') {
window.location.assign('/login')
}
}
/**
* @param {string} path
* @param {RequestInit & { auth?: boolean }} options - set auth: true to send Bearer and refresh on 401
*/
export async function apiJson(path, options = {}) {
const { auth = false, ...fetchOpts } = options
function buildHeaders() {
const h = {
'Content-Type': 'application/json',
...(fetchOpts.headers || {}),
}
if (auth) {
const access = getAccessToken()
if (access) {
h.Authorization = `Bearer ${access}`
}
}
return h
}
const url = apiUrl(path)
let res = await fetch(url, {
...fetchOpts,
headers: buildHeaders(),
})
if (res.status === 401 && auth) {
const data = await postRefresh()
if (data?.access_token && data?.refresh_token) {
setSession({
access_token: data.access_token,
refresh_token: data.refresh_token,
user: getStoredUser(),
})
res = await fetch(url, {
...fetchOpts,
headers: buildHeaders(),
})
} else {
redirectToLogin()
throw new Error('Session expired')
}
}
if (!res.ok) {
if (res.status === 401 && auth) {
redirectToLogin()
}
throw new Error(await readDetail(res))
}
if (res.status === 204) return null
const text = await res.text()
return text ? JSON.parse(text) : null
}
|