![](/img/trans.png)
[英]Chrome local IndexedDB (PouchDB) replication to CouchDB problem
[英]How to detect PouchDB IndexedDB adapter for existing DB
我有一个使用“idb”适配器的现有用户群。 对于新用户,我想使用“indexeddb”适配器创建数据库。 我需要找到一种方法来确定现有数据库使用的适配器,因为它可能是这两个中的任何一个。
要查找现有 PouchDB 数据库的当前适配器,您需要使用本机 IndexedDB API。 直接使用 PouchDB 是行不通的,因为它在数据库不存在时会创建数据库,当它是另一个版本时会失败。
下面的代码应该是诀窍(TypeScript)。
async function getCurrentAdapterForDb(dbname: string): Promise<string> {
return new Promise<undefined | "idb" | "indexeddb">((resolve, reject) => {
// To detect whether the database is using idb or indexeddb, we look at the version property of the indexeddb
// If the database does not exists ==> onupgradeneeded is called with oldVersion = 0 (requesting version 1)
// If the database exists, a version below Math.pow(10, 13) is considered idb. A version above is considered indexeddb.
let request = window.indexedDB.open(`_pouch_${dbname}`);
request.onupgradeneeded = function (e: IDBVersionChangeEvent): void {
// Since no version has been requested, this mean the database do not exists.
if (e.oldVersion === 0) {
resolve(undefined); // Database does not exists
}
// We do not want the database to be created or migrated here, this is only a check. Therefore, abort the transaction.
request.transaction.abort();
};
request.onerror = function (err: Event): void {
if (request.error.code !== request.error.ABORT_ERR) {
// Abort Error has been triggered above. Ignoring since we already resolved the promise.
reject(request.error);
}
};
request.onsuccess = function (): void {
// When the database is successfully opened, we detect the adapter using the version
// If we are dealing with a new database, oldVersion will be 0.
// If we are dealing with an existing database, oldVersion will be less than indexedDbStartVersion.
// indexedDbStartVersion is taken from pouchdb-adapter-indexeddb/index.es.js -- v7.2.2
let indexedDbStartVersion = Math.pow(10, 13);
if (request.result.version < indexedDbStartVersion) {
resolve("idb");
} else {
resolve("indexeddb");
}
// Closes the database
request.result.close();
};
})
}
请同时在浏览器中查看 PouchDB :
console.log(yourPouchDBinstance.adapter);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.