Last active
October 18, 2016 01:13
-
-
Save ignasbernotas/c2af5b6553f4b63b07f8ccfe03e35a43 to your computer and use it in GitHub Desktop.
Dexie relationship loading plugin
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
import Dexie from 'dexie' | |
/** | |
* Usage: db.table_a.with('table_a_children', 'parent_id', 'children', 'id') | |
* | |
* This will return all items from table 'table_a' | |
* where each item will have a 'children' array with linked records from 'table_a_children' table | |
*/ | |
Dexie.addons.push((db) => { | |
/** | |
* Iterate through all items and collect related records | |
* | |
* @param table | |
* @param column | |
* @param asProperty | |
* @param searchProperty | |
* | |
* @returns {Dexie.Promise} | |
*/ | |
db.Table.prototype.with = function (table, column, asProperty, searchProperty) { | |
return this.toCollection().with(table, column, asProperty, searchProperty) | |
} | |
/** | |
* Iterate through all items and collect related records | |
* | |
* @param table | |
* @param column | |
* @param asProperty | |
* @param searchProperty | |
* | |
* @returns {Dexie.Promise} | |
*/ | |
db.Collection.prototype.with = function (table, column, asProperty, searchProperty) { | |
var self = this | |
searchProperty = searchProperty || 'id' | |
return new Dexie.Promise((resolve, reject) => { | |
self.toArray().then(rows => { | |
var length = rows.length | |
// loop through all rows and collect all data from the related table | |
rows.forEach((row, index) => { | |
let load = db._allTables[table] | |
.where(column) | |
.equals(row[searchProperty]) | |
.toArray() | |
load.then(children => { | |
rows[index][asProperty] = children | |
// once the collection of related items is done, resolve the promise | |
if (index + 1 === length) { | |
resolve(rows) | |
} | |
}) | |
}) | |
}) | |
}) | |
} | |
}) | |
export default Dexie |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment