react-native-onyx
Version:
State management for React Native
53 lines (52 loc) • 2.46 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const idb_keyval_1 = require("idb-keyval");
const Logger_1 = require("../../../Logger");
// This is a copy of the createStore function from idb-keyval, we need a custom implementation
// because we need to create the database manually in order to ensure that the store exists before we use it.
// If the store does not exist, idb-keyval will throw an error
// source: https://github.com/jakearchibald/idb-keyval/blob/9d19315b4a83897df1e0193dccdc29f78466a0f3/src/index.ts#L12
function createStore(dbName, storeName) {
let dbp;
const getDB = () => {
if (dbp)
return dbp;
const request = indexedDB.open(dbName);
request.onupgradeneeded = () => request.result.createObjectStore(storeName);
dbp = (0, idb_keyval_1.promisifyRequest)(request);
dbp.then((db) => {
// It seems like Safari sometimes likes to just close the connection.
// It's supposed to fire this event when that happens. Let's hope it does!
// eslint-disable-next-line no-param-reassign
db.onclose = () => (dbp = undefined);
},
// eslint-disable-next-line @typescript-eslint/no-empty-function
() => { });
return dbp;
};
// Ensures the store exists in the DB. If missing, bumps the version to trigger
// onupgradeneeded, recreates the store, and returns a promise to the new DB.
const verifyStoreExists = (db) => {
if (db.objectStoreNames.contains(storeName)) {
return db;
}
(0, Logger_1.logInfo)(`Store ${storeName} does not exist in database ${dbName}.`);
const nextVersion = db.version + 1;
db.close();
const request = indexedDB.open(dbName, nextVersion);
request.onupgradeneeded = () => {
const updatedDatabase = request.result;
if (updatedDatabase.objectStoreNames.contains(storeName)) {
return;
}
(0, Logger_1.logInfo)(`Creating store ${storeName} in database ${dbName}.`);
updatedDatabase.createObjectStore(storeName);
};
dbp = (0, idb_keyval_1.promisifyRequest)(request);
return dbp;
};
return (txMode, callback) => getDB()
.then(verifyStoreExists)
.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
}
exports.default = createStore;