File size: 3,653 Bytes
c5cf697
 
 
 
 
 
 
2b32e9d
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b32e9d
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import {
  clearAdminSession,
  getAdminAccessToken,
  getAdminRefreshToken,
  getStoredAdmin,
  setAdminSession,
} from '../auth/adminStorage'
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 postAdminRefresh() {
  const rt = getAdminRefreshToken()
  if (!rt) return null
  const res = await fetch(apiUrl('/admin/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 redirectToAdminLogin() {
  clearAdminSession()
  if (typeof window !== 'undefined') {
    window.location.assign('/admin/login')
  }
}

export async function apiAdminJson(path, options = {}) {
  const { auth = false, ...fetchOpts } = options

  function buildHeaders() {
    const h = {
      'Content-Type': 'application/json',
      ...(fetchOpts.headers || {}),
    }
    if (auth) {
      const access = getAdminAccessToken()
      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 postAdminRefresh()
    if (data?.access_token && data?.refresh_token) {
      setAdminSession({
        access_token: data.access_token,
        refresh_token: data.refresh_token,
        admin: getStoredAdmin(),
      })
      res = await fetch(url, {
        ...fetchOpts,
        headers: buildHeaders(),
      })
    } else {
      redirectToAdminLogin()
      throw new Error('Session expired')
    }
  }

  if (!res.ok) {
    if (res.status === 401 && auth) {
      redirectToAdminLogin()
    }
    throw new Error(await readDetail(res))
  }

  if (res.status === 204) return null
  const text = await res.text()
  return text ? JSON.parse(text) : null
}

/**
 * Multipart POST; pass a factory so body can be recreated after token refresh.
 * @param {string} path
 * @param {() => FormData} formDataFactory
 * @param {{ auth?: boolean }} options
 */
export async function apiAdminUpload(path, formDataFactory, options = {}) {
  const { auth = false } = options

  function authHeaders() {
    const h = {}
    if (auth) {
      const access = getAdminAccessToken()
      if (access) {
        h.Authorization = `Bearer ${access}`
      }
    }
    return h
  }

  const uploadUrl = apiUrl(path)
  let res = await fetch(uploadUrl, {
    method: 'POST',
    headers: authHeaders(),
    body: formDataFactory(),
  })

  if (res.status === 401 && auth) {
    const data = await postAdminRefresh()
    if (data?.access_token && data?.refresh_token) {
      setAdminSession({
        access_token: data.access_token,
        refresh_token: data.refresh_token,
        admin: getStoredAdmin(),
      })
      res = await fetch(uploadUrl, {
        method: 'POST',
        headers: authHeaders(),
        body: formDataFactory(),
      })
    } else {
      redirectToAdminLogin()
      throw new Error('Session expired')
    }
  }

  if (!res.ok) {
    if (res.status === 401 && auth) {
      redirectToAdminLogin()
    }
    throw new Error(await readDetail(res))
  }

  const text = await res.text()
  return text ? JSON.parse(text) : null
}