2022-11-20 23:50:08 +08:00

62 lines
1.5 KiB
TypeScript

import config from "../config";
import log from "./log";
export class BizError extends Error {
code: number;
constructor(message: string, code = 500) {
super(message);
this.code = code;
}
}
type ApiResponse<T> = {
code: 0 | number
message: string
data: T
}
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE"
function request<T>(api: string, data: any = null, method: HttpMethod = 'POST') {
const header: {
[key: string]: string
} = {}
// 判断是否有token
const token = getApp().globalData.token
if (token) { // 如果有token 添加token头
header.token = token
}
// 对于post请求发送json数据
if (method === 'POST') {
header['content-type'] = 'application/json'
}
return new Promise((resolve, reject) => {
wx.request<ApiResponse<T>>({
url: config.api_url + api,
data,
header,
method,
success: (res) => {
// 验证http的响应码是否正常
if (res.statusCode !== 200) {
reject(new BizError('请求数据失败(server)', -1))
return;
}
if(!res.data){
reject(new BizError('请求数据失败(empty)', -1))
return;
}
const result = res.data
// 验证接口是否正确
if (result.code !== 0) {
reject(new BizError(result.message, result.code))
return;
}
resolve(result.data)
},
fail: (e) => {
log(e)
reject(new BizError('请求数据失败(http)', -1))
}
})
})
}
export default request