繁体   English   中英

PouchDB - 懒惰地获取和复制文档

[英]PouchDB - Lazily fetch and replicate documents

TL; DR:我想要一个像Ember Data一样的PouchDB数据库:首先从本地存储中获取,如果没有找到,则转到远程数据库。 在两种情况下复制该文档。

我在PouchDB / CouchDB服务器中有一个名为Post文档类型。 我希望PouchDB查看本地存储,如果它有文档,则返回文档并开始复制。 如果没有,请转到远程CouchDB服务器,获取文档,将其存储在本地PouchDB实例中,然后开始仅复制该文档。 在这种情况下,我不想复制整个数据库,只需要用户已经获取的内容。

我可以通过写这样的东西来实现它:

var local = new PouchDB('local');
var remote = new PouchDB('http://localhost:5984/posts');

function getDocument(id) {
  return local.get(id).catch(function(err) {
    if (err.status === 404) {
      return remote.get(id).then(function(doc) {
        return local.put(id);
      });
    }
    throw error;
  });
}

这也不能处理复制问题,但它是我想要做的总体方向。

我可以自己编写这段代码,但我想知道是否有一些内置方法可以做到这一点。

不幸的是,你所描述的并不存在(至少作为内置函数)。 你绝对可以使用上面的代码从本地回到远程(这是完美的BTW :)),但是local.put()会给你带来问题,因为本地doc最终会得到与远程doc不同的_rev ,可能会在以后混乱复制(它将被解释为冲突)。

您应该能够使用{revs: true}来获取带有修订历史记录的文档,然后使用{new_edits: false}插入以正确复制丢失的文档,同时保留修订历史记录(这是复制器在引擎盖下执行的操作) 。 这看起来像这样:

var local = new PouchDB('local');
var remote = new PouchDB('http://localhost:5984/posts');

function getDocument(id) {
  return local.get(id).catch(function(err) {
    if (err.status === 404) {
      // revs: true gives us the critical "_revisions" object,
      // which contains the revision history metadata
      return remote.get(id, {revs: true}).then(function(doc) {
        // new_edits: false inserts the doc while preserving revision
        // history, which is equivalent to what replication does
        return local.bulkDocs([doc], {new_edits: false});
      }).then(function () {
        return local.get(id); // finally, return the doc to the user
      });
    }
    throw error;
  });
}

这应该工作! 如果有帮助,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM