PouchDB - 延迟获取和复制文档

Sta*_*art 3 javascript couchdb pouchdb

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

Post我的 PouchDB/CouchDB 服务器中有一个名为的文档类型。我希望 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;
  });
}
Run Code Online (Sandbox Code Playgroud)

这也不能解决复制问题,但这是我想做的事情的总体方向。

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

nla*_*son 5

不幸的是,您所描述的并不完全存在(至少作为内置函数)。您绝对可以使用上面的代码从本地回退到远程(顺便说一句,这是完美的:)),但local.put()会给您带来问题,因为本地文档最终将与_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;
  });
}
Run Code Online (Sandbox Code Playgroud)

那应该有效!让我知道这是否有帮助。