update the new school year model
This commit is contained in:
+35
-3
@@ -11,6 +11,25 @@ export function setStoredToken(token: string | null): void {
|
||||
else localStorage.removeItem(TOKEN_KEY)
|
||||
}
|
||||
|
||||
export function decodeJwtPayload<T = unknown>(token: string): T | null {
|
||||
try {
|
||||
const payload = token.split('.')[1]
|
||||
if (!payload) return null
|
||||
|
||||
const base64 = payload.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const json = decodeURIComponent(
|
||||
atob(base64)
|
||||
.split('')
|
||||
.map((char) => `%${char.charCodeAt(0).toString(16).padStart(2, '0')}`)
|
||||
.join(''),
|
||||
)
|
||||
|
||||
return JSON.parse(json) as T
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiHttpError extends Error {
|
||||
readonly status: number
|
||||
readonly body: unknown
|
||||
@@ -30,24 +49,36 @@ export async function apiFetch<T>(
|
||||
): Promise<T> {
|
||||
const attachAuth = opts.attachAuth !== false
|
||||
const headers = new Headers(init.headers)
|
||||
if (!headers.has('Accept')) headers.set('Accept', 'application/json')
|
||||
|
||||
if (!headers.has('Accept')) {
|
||||
headers.set('Accept', 'application/json')
|
||||
}
|
||||
|
||||
const token = getStoredToken()
|
||||
|
||||
if (attachAuth && token && !headers.has('Authorization')) {
|
||||
headers.set('Authorization', `Bearer ${token}`)
|
||||
}
|
||||
|
||||
const url = apiUrl(path)
|
||||
|
||||
let res: Response
|
||||
|
||||
try {
|
||||
res = await fetch(url, { ...init, headers })
|
||||
res = await fetch(url, {
|
||||
...init,
|
||||
headers,
|
||||
})
|
||||
} catch (e) {
|
||||
const hint = import.meta.env.DEV
|
||||
? ' Start the API and ensure Vite can reach it (see vite.config.ts; default proxy is http://localhost:8080 unless VITE_PROXY_API is set).'
|
||||
? ' Start the API and ensure Vite can reach it. Default proxy is http://localhost:8000 unless VITE_PROXY_API or VITE_API_ORIGIN is set.'
|
||||
: ''
|
||||
|
||||
const reason = e instanceof Error ? e.message : 'Failed to fetch'
|
||||
|
||||
throw new ApiHttpError(`Network error: ${reason}.${hint}`, 0, null)
|
||||
}
|
||||
|
||||
const body: unknown = await res.json().catch(() => null)
|
||||
|
||||
if (!res.ok) {
|
||||
@@ -55,6 +86,7 @@ export async function apiFetch<T>(
|
||||
typeof body === 'object' && body !== null && 'message' in body
|
||||
? String((body as { message?: unknown }).message ?? '')
|
||||
: ''
|
||||
|
||||
throw new ApiHttpError(msg || `HTTP ${res.status}`, res.status, body)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user