69 lines
2.1 KiB
JavaScript
69 lines
2.1 KiB
JavaScript
import { getToken } from './auth.js'
|
|
|
|
const API_BASE = (import.meta.env?.VITE_API_BASE || '/api').replace(/\/$/, '')
|
|
|
|
function unwrap(body) {
|
|
if (body == null || typeof body !== 'object') {
|
|
throw new Error('网络异常,请稍后重试')
|
|
}
|
|
if (body.code === 200) return body.data
|
|
throw new Error((body.message && String(body.message).trim()) || '请求失败')
|
|
}
|
|
|
|
export async function request({ url, method = 'GET', data, headers = {}, signal }) {
|
|
const path = url.startsWith('/') ? url : `/${url}`
|
|
const full = `${API_BASE}${path}`
|
|
const token = getToken()
|
|
if (!token) {
|
|
throw new Error('未携带登录态,请从小程序入口打开')
|
|
}
|
|
const init = {
|
|
method: method.toUpperCase(),
|
|
signal,
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
...headers
|
|
}
|
|
}
|
|
if (data instanceof FormData) {
|
|
init.body = data
|
|
} else if (data != null && init.method !== 'GET') {
|
|
init.headers['Content-Type'] = 'application/json'
|
|
init.body = JSON.stringify(data)
|
|
}
|
|
let finalUrl = full
|
|
if (init.method === 'GET' && data && typeof data === 'object') {
|
|
const q = new URLSearchParams()
|
|
Object.entries(data).forEach(([k, v]) => {
|
|
if (v != null && v !== '') q.set(k, String(v))
|
|
})
|
|
const s = q.toString()
|
|
if (s) finalUrl += (finalUrl.includes('?') ? '&' : '?') + s
|
|
}
|
|
const res = await fetch(finalUrl, init)
|
|
const body = await res.json().catch(() => null)
|
|
if (res.status === 401) {
|
|
throw new Error('登录已失效,请返回小程序重新登录')
|
|
}
|
|
if (body && typeof body === 'object' && body.detail && body.code == null) {
|
|
throw new Error(
|
|
res.status === 401 || /not authenticated/i.test(String(body.detail))
|
|
? '登录已失效,请返回小程序重新登录'
|
|
: String(body.detail)
|
|
)
|
|
}
|
|
return unwrap(body)
|
|
}
|
|
|
|
export function get(url, params) {
|
|
return request({ url, method: 'GET', data: params })
|
|
}
|
|
|
|
export function post(url, data) {
|
|
return request({ url, method: 'POST', data })
|
|
}
|
|
|
|
export function put(url, data) {
|
|
return request({ url, method: 'PUT', data })
|
|
}
|