import { env, TIMEOUT } from '@/common/env.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 } 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 } uni.request({ url: env.baseUrl + options.url, method: options.method ?? 'GET', data: options.data, header: header, timeout: TIMEOUT, success: (res) => { const statusCode = res.statusCode if (statusCode >= 200 && statusCode < 300) { const body = res.data as UTSJSONObject const code = body.getNumber('code') if (code != null && code == 200) { resolve(body.get('data') as T) } else { const msg = body.getString('message') ?? '请求失败' uni.showToast({ title: msg, icon: 'none' }) reject(new Error(msg)) } } else { const msg = '网络错误 ' + statusCode uni.showToast({ title: msg, icon: 'none' }) reject(new Error(msg)) } }, fail: (err) => { const msg = err.errMsg ?? '请求失败' uni.showToast({ title: msg, icon: 'none' }) 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 }) }