import type { ApiResponse, HttpMethod, RequestOptions } from './types' import { BASE_URL, TIMEOUT } from './config' export type { ApiResponse, RequestOptions } let _loadingCount = 0 const _showLoading = (title: string): void => { if (_loadingCount === 0) wx.showLoading({ title, mask: true }) _loadingCount++ } const _hideLoading = (): void => { if (_loadingCount > 0) _loadingCount-- if (_loadingCount === 0) wx.hideLoading() } const request = ( url: string, data?: Record, method: HttpMethod = 'GET', options: RequestOptions = {}, ): Promise> => { const { loading = true, loadingTitle = '加载中...', contentType = 'application/json' } = options if (loading) _showLoading(loadingTitle) const header: Record = { 'content-type': contentType } const token = wx.getStorageSync('token') as string if (token) header['X-Access-Token'] = token return new Promise((resolve, reject) => { wx.request({ url: BASE_URL + url, data, method, header, timeout: TIMEOUT, success: (res) => { if (loading) _hideLoading() const body = res.data as ApiResponse const code = body.code // 兼容两种后端返回风格:code 200(自定义)或 code 0(jeecg) if (code === 200 || code === 0 || code === '0') { resolve(body) } else { wx.showToast({ title: body.msg || body.message || '请求失败', icon: 'none' }) reject(body) } }, fail: (err) => { if (loading) _hideLoading() wx.showToast({ title: '网络异常,请重试', icon: 'none' }) reject(err) }, }) }) } export const get = ( url: string, data?: Record, options?: RequestOptions, ): Promise> => request(url, data, 'GET', options) export const post = ( url: string, data?: Record, options?: RequestOptions, ): Promise> => request(url, data, 'POST', options) export const put = ( url: string, data?: Record, options?: RequestOptions, ): Promise> => request(url, data, 'PUT', options)