Эх сурвалжийг харах

接口返回401,重新调用 code2token 接口

cc12458 1 жил өмнө
parent
commit
83a3f4a2ff

+ 2 - 2
miniprogram/lib/logic.ts

@@ -11,10 +11,10 @@ export function token() {
   return TOKEN.data || wx.getStorageSync(TOKEN.key)
 }
 
-export async function login(force?: boolean) {
+export async function login(force?: boolean, title = '登录中') {
   const _token = force ? '' : await wx.checkSession().then(() => token(), () => '');
   if (_token) return _token;
-  const show = setTimeout(() => wx.showLoading({ title: '登录中' }), 300);
+  const show = setTimeout(() => wx.showLoading({ title }), 300);
   try {
     const { code } = await _login();
 

+ 17 - 2
miniprogram/lib/request/create.ts

@@ -1,3 +1,4 @@
+import { login } from "../logic";
 import { request as _request } from "../wx/network";
 
 const shareRequestCache = new Map<string, IRequestData<any>>();
@@ -5,7 +6,7 @@ const shareRequestCache = new Map<string, IRequestData<any>>();
 export function createRequest(option: IRequestCreateConfig) {
   const { baseURL } = option;
 
-  return async <R, T>(config: IRequestConfig<R, T>) => {
+  return async function request<R, T>(config: IRequestConfig<R, T>) {
     let { url, data, params, header, meta, transform = (params: any) => params, shareRequest, ..._config } = config;
 
     if (config.method === 'GET') {
@@ -43,6 +44,20 @@ export function createRequest(option: IRequestCreateConfig) {
 
     if (shareRequest) shareRequestCache.set(key, <any>promise);
 
-    return promise;
+    return (promise as any).catch(async (error: { errno: string }) => {
+      shareRequestCache.delete(key);
+      if (error.errno === '060201401') {
+        await login(true, '重新登录中');
+        wx.showLoading({ title: '重新加载中', });
+        try {
+          return await request(config);
+        } catch (error) {
+          throw error;
+        } finally {
+          wx.hideLoading();
+        }
+      }
+      throw error;
+    });
   }
 }