import { refreshToken } from '../core/libs/requests' import { CustomRequestOptions } from '../interceptors/request' import { useUserStore } from '../store' import dayjs from 'dayjs' export const http = async (options: CustomRequestOptions) => { const userStore = useUserStore() const Authorization = userStore.userInfo?.token const header: { 'tenant-id': number; Authorization?: string } = { 'tenant-id': 1, Authorization, } // console.log(dayjs(userStore.userInfo.expiresTime).format('YYYY-MM-DD HH:mm:ss')) const diff = dayjs(userStore.userInfo.expiresTime).diff(dayjs(), 'minutes') // console.log(diff) if (userStore.isLogined && diff < 10 && options.url !== '/app-api/member/auth/refresh-token') { const { data } = await refreshToken(userStore.userInfo.refreshToken) userStore.setUserInfo({ ...userStore.userInfo, token: data.accessToken, userId: data.userId, accessToken: data.accessToken, refreshToken: data.refreshToken, expiresTime: data.expiresTime, // openid: data.openid, }) } // 1. 返回 Promise 对象 return new Promise>((resolve, reject) => { uni.request({ ...options, header, dataType: 'json', // #ifndef MP-WEIXIN responseType: 'json', // #endif // 响应成功 success(res) { // console.log(res) // 状态码 2xx,参考 axios 的设计 if (res.statusCode >= 200 && res.statusCode < 300) { // 2.1 提取核心数据 res.data if ((res.data as IResData).code === 0) { resolve(res.data as IResData) } else if ((res.data as IResData).code === 401) { userStore.clearUserInfo() uni.navigateTo({ url: '/pages-sub/login/index' }) reject(res) } else { !options.hideErrorToast && uni.showToast({ icon: 'none', title: (res.data as IResData).msg || '请求错误', }) reject(res.data) } } else if (res.statusCode === 401) { // 401错误 -> 清理用户信息,跳转到登录页 userStore.clearUserInfo() reject(res) } else { // 其他错误 -> 根据后端错误信息轻提示 !options.hideErrorToast && uni.showToast({ icon: 'none', title: (res.data as IResData).msg || '请求错误', }) reject(res) } }, // 响应失败 fail(err) { uni.showToast({ icon: 'none', title: '网络错误,换个网络试试', }) reject(err) }, }) }) } /** * GET 请求 * @param url 后台地址 * @param query 请求query参数 * @returns */ export const httpGet = (url: string, query?: Record) => { return http({ url, query, method: 'GET', }) } /** * POST 请求 * @param url 后台地址 * @param data 请求body参数 * @param query 请求query参数,post请求也支持query,很多微信接口都需要 * @returns */ export const httpPost = ( url: string, data?: Record, query?: Record, ) => { return http({ url, query, data, method: 'POST', }) } export const httpPut = (url: string, data?: Record) => http({ url, query: {}, data, method: 'PUT', }) export const httpDelete = (url: string, query?: Record) => http({ url, query, method: 'DELETE' }) http.get = httpGet http.post = httpPost