policeSecurity/collect_information/src/request/index.ts

90 lines
2.5 KiB
TypeScript

import Taro from "@tarojs/taro";
import {ApiOptions} from "../../types/request";
import {type} from "os";
const requestInterceptor = (chain: Taro.Chain) => {
const requestParams = chain.requestParams
const token = Taro.getStorageSync('token')
if (token) {
requestParams.header = {
...requestParams.header,
token: token.value
}
}
return chain.proceed(requestParams)
}
class CustomRequest {
BASE_API: string
public constructor() {
this.BASE_API = process.env.TARO_APP_BASE_API
Taro.addInterceptor(requestInterceptor)
}
private request<T>(url: string, method: keyof Taro.request.Method, options: ApiOptions, params?: object,): Promise<JsonResult<T>> {
return new Promise<JsonResult<T>>((resolve, reject) => {
if (options.loading) {
Taro.showLoading({
title: '请求中...',
}).then()
}
Taro.request<JsonResult<T>, object>({
url: this.BASE_API + url,
data: params,
method,
...options,
success: (result) => {
Taro.hideLoading()
const jsonResult = result.data
if (jsonResult.code !== 200) {
if ([401].includes(jsonResult.code)) {
//todo 重新登录 跳转登录页 提示错误
}
Taro.showToast({
title: jsonResult.message,
icon: 'none',
mask: true,
duration: 2000
}).then()
reject(jsonResult);
}
resolve(jsonResult);
},
fail: (res) => {
Taro.hideLoading()
Taro.showToast({
title: res.errMsg,
icon: 'none',
mask: true,
duration: 2000
}).then()
reject(res.errMsg);
console.log(res.errMsg, '000')
}
})
})
}
get<T>(url: string, params?: object, options: ApiOptions = {loading: false}): Promise<JsonResult<T>> {
return this.request<T>(url, "GET", options, params)
}
post<T>(url: string, params?: object, options: ApiOptions = {loading: false}): Promise<JsonResult<T>> {
return this.request<T>(url, "POST", options, params)
}
delete<T>(url: string, params?: object, options: ApiOptions = {loading: false}): Promise<JsonResult<T>> {
return this.request(url, "DELETE", options, params)
}
put<T>(url: string, params?: object, options: ApiOptions = {loading: false}): Promise<JsonResult<T>> {
return this.request(url, "PUT", options, params)
}
}
const api = new CustomRequest();
export default api