Files
coffeechat/miniprogram/utils/api.ts
T
2026-09-21 16:01:26 +08:00

32 lines
1.4 KiB
TypeScript

import { apiBaseUrl } from '../config'
interface RequestOptions { method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; data?: unknown }
interface UploadResult { url: string }
export function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
return new Promise((resolve, reject) => wx.request({
url: apiBaseUrl + path,
method: (options.method || 'GET') as WechatMiniprogram.RequestOption['method'],
data: options.data as WechatMiniprogram.IAnyObject,
header: { 'content-type': 'application/json', Authorization: `Bearer ${wx.getStorageSync('token') || ''}` },
success: (response) => response.statusCode >= 200 && response.statusCode < 300
? resolve(response.data as T)
: reject(new Error((response.data as { error?: string })?.error || '网络请求失败')),
fail: reject
}))
}
export function upload(filePath: string): Promise<UploadResult> {
return new Promise((resolve, reject) => wx.uploadFile({
url: apiBaseUrl + '/api/uploads', filePath, name: 'files',
header: { Authorization: `Bearer ${wx.getStorageSync('token') || ''}` },
success: (response) => {
const data = JSON.parse(response.data || '{}') as { files?: UploadResult[]; error?: string }
response.statusCode < 300 && data.files?.[0] ? resolve(data.files[0]) : reject(new Error(data.error || '上传失败'))
},
fail: reject
}))
}
export { apiBaseUrl }