Skip to content

Instantly share code, notes, and snippets.

@javisperez
Last active March 31, 2018 21:45
Show Gist options
  • Save javisperez/5fdd8d149bbcadb35362ddc1683456f8 to your computer and use it in GitHub Desktop.
Save javisperez/5fdd8d149bbcadb35362ddc1683456f8 to your computer and use it in GitHub Desktop.
Dexie js - some useful methods
/**
* I'll update this gist as I get to define more helpful methods to extend
*/
/**
* insertReplace, looks for unique keys on the table and the data to insert
* if the current key/value pair is found (and unique) update it with the given data,
* otherwise insert it as a new record
*/
db.Table.prototype.insertReplace = function(data) {
Object.keys(data).forEach(key => {
const indexes = this.schema.idxByName;
const table = this.name;
if (!indexes[key] || !indexes[key].unique) {
return;
}
db.transaction('rw', db[table], async () => {
const params = {};
params[key] = data[key];
const row = await db[table].get(params);
if (row) {
data.id = row.id;
}
db[table].put(data);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment