Files
bodyWeight/miniprogram/utils/request/index.ts
T
17792275749andClaude Sonnet 4.6 83d909b95b refactor: 项目重构,仅保留 login 和 supplementPersonal 页面
删除 11 个旧页面、组件、lefu SDK、旧资源文件。
新增 request 封装(GET/POST/PUT)、api 层、utils/common 身份证工具。
重写 login(登录流程提取到 app.ts) 和 supplementPersonal(简化表单逻辑)。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-08-10 14:21:00 +08:00

75 lines
2.2 KiB
TypeScript

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 = <T = any>(
url: string,
data?: Record<string, any>,
method: HttpMethod = 'GET',
options: RequestOptions = {},
): Promise<ApiResponse<T>> => {
const { loading = true, loadingTitle = '加载中...', contentType = 'application/json' } = options
if (loading) _showLoading(loadingTitle)
const header: Record<string, string> = { 'content-type': contentType }
const token = wx.getStorageSync('token') as string
if (token) header['abtoken'] = 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<T>
if (body.code === '00000') {
resolve(body)
} else {
wx.showToast({ title: body.msg || '请求失败', icon: 'none' })
reject(body)
}
},
fail: (err) => {
if (loading) _hideLoading()
wx.showToast({ title: '网络异常,请重试', icon: 'none' })
reject(err)
},
})
})
}
export const get = <T = any>(
url: string,
data?: Record<string, any>,
options?: RequestOptions,
): Promise<ApiResponse<T>> => request<T>(url, data, 'GET', options)
export const post = <T = any>(
url: string,
data?: Record<string, any>,
options?: RequestOptions,
): Promise<ApiResponse<T>> => request<T>(url, data, 'POST', options)
export const put = <T = any>(
url: string,
data?: Record<string, any>,
options?: RequestOptions,
): Promise<ApiResponse<T>> => request<T>(url, data, 'PUT', options)