Last active
March 31, 2018 21:45
-
-
Save javisperez/5fdd8d149bbcadb35362ddc1683456f8 to your computer and use it in GitHub Desktop.
Dexie js - some useful methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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