83 lines
2.1 KiB
TypeScript
83 lines
2.1 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;
|
|
}
|
|
}
|
|
export type DataList<T> = {
|
|
records: T[];
|
|
total: number;
|
|
size: number;
|
|
current: number;
|
|
orders: any[];
|
|
optimizeCountSql: boolean;
|
|
searchCount: boolean;
|
|
countId?: any;
|
|
maxLimit?: any;
|
|
pages: number;
|
|
}
|
|
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',autoShowLogin: boolean = true) {
|
|
const header: {
|
|
[key: string]: string
|
|
} = {}
|
|
const app = getApp();
|
|
// 判断是否有token
|
|
const token = app ? app.globalData.token : wx.getStorageSync('user-token')
|
|
if (token) { // 如果有token 添加token头
|
|
header.token = token
|
|
}
|
|
// 对于post请求发送json数据
|
|
if (method !== 'POST') {
|
|
header['content-type'] = 'application/json'
|
|
}
|
|
return new Promise<T>((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) {
|
|
if (result.code === 403 && autoShowLogin) {
|
|
wx.switchTab({
|
|
url: '/pages/personal/personal'
|
|
})
|
|
return;
|
|
}
|
|
reject(new BizError(result.message, result.code))
|
|
return;
|
|
}
|
|
// 请求成功 直接回调
|
|
resolve(result.data)
|
|
},
|
|
fail: (e) => {
|
|
log(e)
|
|
reject(new BizError('请求数据失败(http)', -1))
|
|
}
|
|
})
|
|
})
|
|
}
|
|
export default request |