3

我有一个本地 RxDB 数据库,我想将它与 CouchDB 连接。除了身份验证之外,一切似乎都运行良好。我不知道如何以不同的方式添加它,然后在数据库 url 中插入凭据:

database.tasks.sync({
        remote: `http://${username}:${pass}@127.0.0.1:5984/tododb`,
      });

我想使用 JWT 身份验证,但找不到如何添加令牌来同步请求。我只找到了一些 PouchDB(pouchdb-authentication 插件)的解决方案,但无法让它与 RxDB 一起使用。

4

1 回答 1

2

RxDB 与 PouchDB 紧密耦合,并在后台使用其同步实现。据我了解,将自定义标头添加到远程 PouchDB 实例(这是在您将 url 作为remote参数传递时为您创建的)的唯一方法sync拦截 HTTP 请求

var db = new PouchDB('http://example.com/dbname', {
  fetch: function (url, opts) {
    opts.headers.set('X-Some-Special-Header', 'foo');
    return PouchDB.fetch(url, opts);
  }
});

PouchDB 复制文档(sync) 还指出:

remoteDB 可以是字符串或 PouchDB 对象。如果您在远程数据库上有一个 fetch 覆盖,您将希望使用 PouchDB 对象而不是字符串,以便使用这些选项。

幸运的是,RxDBRx.Collection.sync不仅接受服务器 url 作为remote参数,还接受另一个 RxCollection 或 PouchDB 实例。

RxDB 甚至重新导出内部使用的 PouchDB 模块,因此您不必安装 PouchDB 作为直接依赖项。

import { ..., PouchDB } from 'rxdb';

// ...


const remotePouch = new PouchDB('http://27.0.0.1:5984/tododb', {
  fetch: function (url, opts) {
    opts.headers.set('Authorization', `Bearer ${getYourJWTToken()}`)
    return PouchDB.fetch(url, opts);
  }
})

database.tasks.sync({
  remote: remotePouch,
});
于 2020-10-23T16:20:11.867 回答