policeSecurity/collect_information/src/request/index.ts

88 lines
2.5 KiB
TypeScript
Raw Normal View History

2024-09-10 11:00:20 +08:00
import Taro from "@tarojs/taro";
import {ApiOptions} from "../../types/request";
const requestInterceptor = (chain: Taro.Chain) => {
const requestParams = chain.requestParams
const token = Taro.getStorageSync('token')
if (token) {
requestParams.header = {
...requestParams.header,
token
}
}
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);
2024-09-11 14:27:30 +08:00
console.log(res.errMsg,'000')
2024-09-10 11:00:20 +08:00
}
})
})
}
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