All files / src useApi.ts

69.23% Statements 9/13
88.88% Branches 8/9
66.66% Functions 2/3
66.66% Lines 8/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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      19x                   234x 234x   46x 46x 46x 44x       44x          
import { useCallback } from 'react'
import { useAuth } from './auth'
 
export const API_BASE = (import.meta.env.VITE_API_BASE ?? '') + '/api/v1'
 
export class SessionExpiredError extends Error {
	constructor() {
		super('Session expired')
		this.name = 'SessionExpiredError'
	}
}
 
export function useApi() {
	const { token, signOut } = useAuth()
	return useCallback(
		async (path: string, init: RequestInit = {}): Promise<Response> => {
			const headers = new Headers(init.headers)
			if (token) headers.set('authorization', `Bearer ${token}`)
			const res = await fetch(`${API_BASE}${path}`, { ...init, headers })
			Iif (res.status === 401 || res.status === 403) {
				signOut()
				throw new SessionExpiredError()
			}
			return res
		},
		[token, signOut],
	)
}