File size: 1,427 Bytes
09a5796
 
 
 
c5d3374
09a5796
 
c5d3374
 
 
09a5796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5d3374
09a5796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useAuthStore } from '../store/authStore'

const API_BASE = ''

async function _silentRefresh(): Promise<boolean> {
  const res = await fetch(`${API_BASE}/api/auth/refresh`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'include',
  })
  if (!res.ok) return false
  const data = await res.json()
  const { user } = useAuthStore.getState()
  if (user) useAuthStore.getState().setAuth(data.access_token, user)
  return true
}

export async function apiFetch(path: string, options: RequestInit = {}): Promise<Response> {
  const token = useAuthStore.getState().accessToken

  const res = await fetch(`${API_BASE}${path}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...options.headers,
    },
    credentials: 'include',
  })

  if (res.status === 401) {
    const refreshed = await _silentRefresh()
    if (!refreshed) {
      useAuthStore.getState().clearAuth()
      window.location.href = '/login'
      return res
    }
    const newToken = useAuthStore.getState().accessToken
    return fetch(`${API_BASE}${path}`, {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        ...(newToken ? { Authorization: `Bearer ${newToken}` } : {}),
        ...options.headers,
      },
      credentials: 'include',
    })
  }

  return res
}