import { env, TIMEOUT } from '@/common/env.uts' import { logout } from '@/store/user.uts' export type ApiResponse = { code : number message : string data : T | null } export type RequestOptions = { url : string method ?: string data ?: UTSJSONObject | null header ?: UTSJSONObject | null showLoading ?: boolean } function getToken() : string { const token = uni.getStorageSync('token') if (token == null) return '' return token as string } function toastError(msg : string) : void { uni.showToast({ title: msg, icon: 'none' }) } function handleUnauthorized() : void { logout() toastError('登录已失效,请重新登录') uni.reLaunch({ url: '/pages/mine/mine' }) } export function request(options : RequestOptions) : Promise { return new Promise((resolve, reject) => { const header : UTSJSONObject = options.header ?? {} header['Content-Type'] = 'application/json' const token = getToken() if (token.length > 0) { header['Authorization'] = 'Bearer ' + token } if (options.showLoading == true) { uni.showLoading({ title: '加载中...' }) } uni.request({ url: env.baseUrl + options.url, method: options.method ?? 'GET', data: options.data, header: header, timeout: TIMEOUT, success: (res) => { if (options.showLoading == true) { uni.hideLoading() } const statusCode = res.statusCode if (statusCode == 401 || statusCode == 403) { handleUnauthorized() reject(new Error('登录已失效')) return } if (statusCode >= 200 && statusCode < 300) { const body = res.data if (body == null || !(body instanceof UTSJSONObject)) { reject(new Error('响应格式错误')) return } const json = body as UTSJSONObject const code = json.getNumber('code') if (code == null) { resolve(json as T) return } if (code == 200) { resolve(json.get('data') as T) } else { const msg = json.getString('message') ?? '请求失败' toastError(msg) reject(new Error(msg)) } } else { const msg = '网络错误 ' + statusCode toastError(msg) reject(new Error(msg)) } }, fail: (err) => { if (options.showLoading == true) { uni.hideLoading() } const msg = err.errMsg != null && err.errMsg.length > 0 ? err.errMsg : '请求失败' toastError(msg) reject(new Error(msg)) } }) }) } export function get(url : string, data ?: UTSJSONObject | null) : Promise { return request({ url: url, method: 'GET', data: data }) } export function post(url : string, data ?: UTSJSONObject | null) : Promise { return request({ url: url, method: 'POST', data: data }) } export function put(url : string, data ?: UTSJSONObject | null) : Promise { return request({ url: url, method: 'PUT', data: data }) } export function del(url : string, data ?: UTSJSONObject | null) : Promise { return request({ url: url, method: 'DELETE', data: data }) }