api.ts 4.55 KB
// API 客户端:自动带登录令牌;令牌过期自动刷新一次;出错抛 ApiError(message = 后端 detail)。
export class ApiError extends Error {
  status: number
  constructor(message: string, status: number) {
    super(message)
    this.status = status
  }
}

const TOKEN = 'rs.access'
const REFRESH = 'rs.refresh'

function store() {
  try { return window.localStorage } catch { return null }
}

export const tokens = {
  get access() { return store()?.getItem(TOKEN) || '' },
  get refresh() { return store()?.getItem(REFRESH) || '' },
  set(a: string, r: string) { store()?.setItem(TOKEN, a); store()?.setItem(REFRESH, r) },
  clear() { store()?.removeItem(TOKEN); store()?.removeItem(REFRESH) },
}

export const hooks = { onUnauthorized: null as null | (() => void) }

let refreshing: Promise<boolean> | null = null
async function tryRefresh(): Promise<boolean> {
  if (!tokens.refresh) return false
  refreshing ??= fetch('/api/auth/refresh', {
    method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ refresh_token: tokens.refresh }),
  }).then(async (r) => {
    if (!r.ok) return false
    const d = await r.json()
    tokens.set(d.access_token, d.refresh_token)
    return true
  }).catch(() => false).finally(() => { setTimeout(() => (refreshing = null), 0) })
  return refreshing
}

type Opts = { raw?: boolean; auth?: boolean }

async function request(method: string, url: string, body?: unknown, opts: Opts = {}, retried = false): Promise<any> {
  const headers: Record<string, string> = {}
  if (opts.auth !== false && tokens.access) headers.Authorization = 'Bearer ' + tokens.access
  let payload: BodyInit | undefined
  if (body instanceof Blob) {
    headers['Content-Type'] = body.type || 'application/octet-stream'
    payload = body
  } else if (body !== undefined) {
    headers['Content-Type'] = 'application/json'
    payload = JSON.stringify(body)
  }
  const r = await fetch(url, { method, headers, body: payload })
  if (r.status === 401 && opts.auth !== false && !retried && !url.startsWith('/api/auth/')) {
    if (await tryRefresh()) return request(method, url, body, opts, true)
    tokens.clear()
    hooks.onUnauthorized?.()
    throw new ApiError('登录已失效,请重新登录', 401)
  }
  if (opts.raw) return r
  const text = await r.text()
  let data: any = null
  try { data = text ? JSON.parse(text) : null } catch { data = text }
  if (!r.ok) {
    const d = data && typeof data === 'object' ? data.detail : data
    const msg = Array.isArray(d)
      ? d.map((x: any) => `${(x.loc || []).slice(-1)[0] || ''} ${x.msg}`).join(';')
      : (d || `请求失败(HTTP ${r.status})`)
    throw new ApiError(String(msg), r.status)
  }
  return data
}

export const api = {
  get: (url: string) => request('GET', url),
  post: (url: string, body?: unknown) => request('POST', url, body ?? {}),
  put: (url: string, body?: unknown) => request('PUT', url, body ?? {}),
  del: (url: string) => request('DELETE', url),
  /** 上传原始文件(请求体就是文件字节,如取数端更新包)。 */
  upload: (url: string, file: Blob) => request('POST', url, file),
  /** 带令牌下载文件(CSV 导出等)。 */
  async download(url: string, filename: string) {
    const r: Response = await request('GET', url, undefined, { raw: true })
    if (!r.ok) throw new ApiError(`下载失败(HTTP ${r.status})`, r.status)
    const blob = await r.blob()
    const a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = filename
    a.click()
    setTimeout(() => URL.revokeObjectURL(a.href), 5000)
  },
  /** 大文件(日志包、诊断包):先用 /api/me 确认令牌有效(过期会自动刷新),再交给浏览器自己下载 ——
   *  流式写盘、不占页面内存,网络中途出错时浏览器的下载栏会给出具体原因,而不是笼统的 "Failed to fetch"。 */
  async saveFile(url: string, filename: string) {
    await request('GET', '/api/me')
    const a = document.createElement('a')
    a.href = api.withToken(url)
    a.download = filename
    document.body.appendChild(a)
    a.click()
    a.remove()
  },
  /** <img> / 新窗口打开受保护的文件:把令牌放进查询参数。 */
  withToken(url: string) {
    return url + (url.includes('?') ? '&' : '?') + 'access_token=' + encodeURIComponent(tokens.access)
  },
}

/** 免登录接口(手机单据页等)。 */
export const publicApi = {
  get: (url: string) => request('GET', url, undefined, { auth: false }),
  post: (url: string, body?: unknown) => request('POST', url, body ?? {}, { auth: false }),
}