File size: 1,516 Bytes
94b4ce6
 
 
5936c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export function api(path: string) {
  return `${import.meta.env.BASE_URL}api/${path.replace(/^\/+/, '')}`
}

const KEY_STORE = 'cut-admin-key'

export function getAdminKey() {
  try {
    return localStorage.getItem(KEY_STORE) || ''
  } catch {
    return ''
  }
}

export function setAdminKey(key: string) {
  try {
    if (key) localStorage.setItem(KEY_STORE, key)
    else localStorage.removeItem(KEY_STORE)
  } catch {
    /* private mode */
  }
}

export class ApiError extends Error {
  status: number
  needsKey: boolean
  constructor(message: string, status: number, needsKey = false) {
    super(message)
    this.status = status
    this.needsKey = needsKey
  }
}

/** JSON request helper; sends the saved admin key and turns error bodies into ApiError. */
export async function request<T = unknown>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> {
  const headers: Record<string, string> = {}
  const key = getAdminKey()
  if (key) headers['x-admin-key'] = key
  if (init.body !== undefined) headers['content-type'] = 'application/json'
  const res = await fetch(api(path), {
    method: init.method || (init.body !== undefined ? 'POST' : 'GET'),
    headers,
    body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
  })
  let body: any = null
  try {
    body = await res.json()
  } catch {
    /* empty body */
  }
  if (!res.ok) throw new ApiError(body?.error || `请求失败(${res.status})`, res.status, Boolean(body?.needsKey))
  return body as T
}