signal-desktop/js/modules/database.js

69 lines
2 KiB
JavaScript
Raw Normal View History

/* global indexedDB */
// Module for interacting with IndexedDB without Backbone IndexedDB adapter
// and using promises. Revisit use of `idb` dependency as it might cover
// this functionality.
const { isObject, isNumber } = require('lodash');
2018-03-29 20:15:23 +00:00
exports.open = (name, version, { onUpgradeNeeded } = {}) => {
const request = indexedDB.open(name, version);
return new Promise((resolve, reject) => {
2018-04-27 21:25:04 +00:00
request.onblocked = () => reject(new Error('Database blocked'));
2018-04-27 21:25:04 +00:00
request.onupgradeneeded = event => {
const hasRequestedSpecificVersion = isNumber(version);
if (!hasRequestedSpecificVersion) {
return;
}
const { newVersion, oldVersion } = event;
if (onUpgradeNeeded) {
const { transaction } = event.target;
onUpgradeNeeded({ oldVersion, transaction });
return;
}
2018-04-27 21:25:04 +00:00
reject(
new Error(
'Database upgrade required:' +
` oldVersion: ${oldVersion}, newVersion: ${newVersion}`
)
);
};
2018-04-27 21:25:04 +00:00
request.onerror = event => reject(event.target.error);
2018-04-27 21:25:04 +00:00
request.onsuccess = event => {
const connection = event.target.result;
resolve(connection);
};
});
};
exports.completeTransaction = transaction =>
new Promise((resolve, reject) => {
transaction.addEventListener('abort', event => reject(event.target.error));
transaction.addEventListener('error', event => reject(event.target.error));
transaction.addEventListener('complete', () => resolve());
});
2018-04-27 21:25:04 +00:00
exports.getVersion = async name => {
2018-03-28 17:09:09 +00:00
const connection = await exports.open(name);
const { version } = connection;
connection.close();
return version;
};
2018-03-29 20:15:23 +00:00
exports.getCount = async ({ store } = {}) => {
if (!isObject(store)) {
2018-04-11 19:44:52 +00:00
throw new TypeError("'store' is required");
2018-03-29 20:15:23 +00:00
}
const request = store.count();
return new Promise((resolve, reject) => {
2018-04-27 21:25:04 +00:00
request.onerror = event => reject(event.target.error);
request.onsuccess = event => resolve(event.target.result);
2018-03-29 20:15:23 +00:00
});
};