Browse Source

fix sync logic, limit requests to 1 per second

Gerald 9 years ago
parent
commit
117e4cf859
2 changed files with 21 additions and 16 deletions
  1. 15 2
      src/background/sync/dropbox.js
  2. 6 14
      src/background/sync/index.js

+ 15 - 2
src/background/sync/dropbox.js

@@ -79,13 +79,26 @@ setTimeout(function () {
     this.headers = {
       Authorization: 'Bearer ' + token,
     };
+    this.lastFetch = 0;
   }
   Dropbox.prototype.fetch = function (input, init) {
+    var _this = this;
     init = init || {};
-    init.headers = _.assign(init.headers || {}, this.headers);
-    return fetch(input, init)
+    init.headers = _.assign(init.headers || {}, _this.headers);
+    var delay = _this.lastFetch + 1000 - Date.now();
+    return new Promise(function (resolve, reject) {
+      if (delay > 0) setTimeout(resolve, delay);
+      else resolve();
+    })
+    .then(function () {
+      _this.lastFetch = Date.now();
+      return fetch(input, init);
+    })
     .then(function (res) {
       return new Promise(function (resolve, reject) {
+        if (res.status === 503) {
+          // TODO Too Many Requests
+        }
         res.status > 300 ? reject(res) : resolve(res);
       });
     });

+ 6 - 14
src/background/sync/index.js

@@ -186,28 +186,20 @@ var sync = function () {
       local.data.forEach(function (item) {
         var remoteItem = map[item.uri];
         if (remoteItem) {
-          if (firstSync || remoteItem.modified <= item.custom.modified) {
-            if (!item.custom.modified) {
-              item.custom.modified = remoteItem.modified;
-              vmdb.saveScript(item);
-            }
-            // up to date
-            delete map[item.uri];
+          if (firstSync || !item.custom.modified || remoteItem.modified > item.custom.modified) {
+            getRemote.push(remoteItem);
+          } else if (remoteItem.modified < item.custom.modified) {
+            putRemote.push(item);
           }
+          delete map[item.uri];
         } else if (firstSync || !outdated) {
           putRemote.push(item);
         } else {
           delLocal.push(item);
         }
-        return map;
       });
       for (var uri in map) {
-        var item = map[uri];
-        if (firstSync || outdated) {
-          getRemote.push(item);
-        } else {
-          delRemote.push(item);
-        }
+        delRemote.push(map[uri]);
       }
       var promises = [].concat(
         getRemote.map(function (item) {