api.ts

2.5 KB v1.0
const TOKEN_KEY = 'crm_pro_token'

export function getToken() { return localStorage.getItem(TOKEN_KEY) }
export function setToken(t: string) { localStorage.setItem(TOKEN_KEY, t) }
export function clearToken() { localStorage.removeItem(TOKEN_KEY) }

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

/** 统一请求封装 */
export async function api<T = any>(path: string, options: {
  method?: string; body?: any; raw?: boolean
} = {}): Promise<T> {
  const { method = 'GET', body, raw } = options
  const headers: Record<string, string> = {}
  const token = getToken()
  if (token) headers.Authorization = `Bearer ${token}`
  if (body !== undefined && !(body instanceof FormData)) {
    headers['Content-Type'] = 'application/json'
  }
  const res = await fetch(path, {
    method, headers,
    body: body === undefined ? undefined : (body instanceof FormData ? body : JSON.stringify(body)),
  })
  if (res.status === 401 && !path.includes('/auth/login')) {
    clearToken()
    // 会话失效,交给 App 层响应
  }
  if (raw) {
    if (!res.ok) throw new ApiError('请求失败', res.status)
    return res as unknown as T
  }
  let data: any
  try { data = await res.json() } catch { data = null }
  if (!res.ok) {
    throw new ApiError(data?.message || `请求失败(${res.status})`, res.status)
  }
  return data as T
}

export const post = <T = any>(p: string, b?: any) => api<T>(p, { method: 'POST', body: b })
export const put = <T = any>(p: string, b?: any) => api<T>(p, { method: 'PUT', body: b })
export const del = <T = any>(p: string) => api<T>(p, { method: 'DELETE' })

/** 下载文件(导出用) */
export async function download(path: string, filename: string) {
  const token = getToken()
  const res = await fetch(path, { headers: token ? { Authorization: `Bearer ${token}` } : {} })
  if (!res.ok) throw new ApiError('下载失败', res.status)
  const blob = await res.blob()
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  a.click()
  URL.revokeObjectURL(url)
}

/** 读取文件为 base64(Excel 导入用) */
export function fileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      const result = reader.result as string
      resolve(result.split(',')[1] || '')
    }
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}