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

api: 403 bind-email 挂起原请求并在绑定成功后自动重放

wenhongquan 1 сар өмнө
parent
commit
cde4382af3
1 өөрчлөгдсөн 15 нэмэгдсэн , 2 устгасан
  1. 15 2
      assets/js/api.js

+ 15 - 2
assets/js/api.js

@@ -1,5 +1,6 @@
 (function () {
   const TOKEN_KEY = 'pouchlab.token.v1';
+  const bindWaiters = [];
 
   function langHeader() {
     const lang = window.PL && window.PL.i18n ? window.PL.i18n.getLang() : 'zh';
@@ -42,8 +43,16 @@
         document.dispatchEvent(new CustomEvent('pl:auth-expired'));
       }
       return res.json().catch(function () { return {}; }).then(function (data) {
+        if (res.status === 403 && data.detail && data.detail.code === 'bind-email') {
+          return new Promise(function (resolve, reject) {
+            bindWaiters.push(function () { request(method, path, body, opts).then(resolve, reject); });
+            document.dispatchEvent(new CustomEvent('pl:bind-email-required',
+              { detail: { message: data.detail.message } }));
+          });
+        }
         if (!res.ok) {
-          const err = new Error(data.detail || tr('请求失败(' + res.status + ')'));
+          const msg = data.detail && data.detail.message ? data.detail.message : data.detail;
+          const err = new Error(msg || tr('请求失败(' + res.status + ')'));
           err.status = res.status;
           throw err;
         }
@@ -119,6 +128,10 @@
     svgToPng: svgToPng,
     get: function (p, o) { return request('GET', p, undefined, o); },
     post: function (p, b, o) { return request('POST', p, b, o); },
-    patch: function (p, b, o) { return request('PATCH', p, b, o); }
+    patch: function (p, b, o) { return request('PATCH', p, b, o); },
+    flushBind: function () {
+      const list = bindWaiters.splice(0);
+      list.forEach(function (run) { try { run(); } catch (e) {} });
+    }
   };
 })();