All files / src useApi.ts

100% Statements 13/13
100% Branches 9/9
100% Functions 3/3
100% Lines 12/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      21x       1x 1x         402x 402x   73x 73x 73x 71x 1x 1x   70x          
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 })
			if (res.status === 401 || res.status === 403) {
				signOut()
				throw new SessionExpiredError()
			}
			return res
		},
		[token, signOut],
	)
}