Last active
March 30, 2019 14:50
-
-
Save oleersoy/5889d0fa70e7f486c05dc8d3a116c426 to your computer and use it in GitHub Desktop.
utilities.ts for dexie
This file contains hidden or 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
| /** | |
| * Load navgiation properties (Email and Phone records) and | |
| * update the ocrresponding ocntact fields. | |
| */ | |
| export async function loadNavigationProperties(contact, db) { | |
| [contact.emails, contact.phones] = await Promise.all([ | |
| db.emails.where('contactId').equals(this.id).toArray(), | |
| db.phones.where('contactId').equals(this.id).toArray() | |
| ]); | |
| } | |
| /** | |
| * Load email records and | |
| * update the corresponding ocntact fields. | |
| */ | |
| export async function loadContactEmails(contact, db) { | |
| contact.emails = | |
| await db.emails.where('contactId').equals(contact.id).toArray(); | |
| } | |
| /** | |
| * Load phone records and | |
| * update the ocrresponding ocntact fields. | |
| */ | |
| export async function loadContactPhones(contact, db) { | |
| contact.phones = | |
| await db.phones.where('contactId').equals(contact.id).toArray(); | |
| } | |
| /** | |
| * Save a contact entity. If email or phone records | |
| * were removed from the contact, then these will also | |
| * be deleted from the database. | |
| */ | |
| export async function save(contact, db) { | |
| return db.transaction('rw', db.contacts, db.emails, db.phones, async() => { | |
| // Add or update contact. If add, record contact.id. | |
| contact.id = await db.contacts.put(contact); | |
| // Save all navigation properties (arrays of emails and phones) | |
| // Some may be new and some may be updates of existing objects. | |
| // put() will handle both cases. | |
| // (record the result keys from the put() operations into emailIds and phoneIds | |
| // so that we can find local deletes) | |
| let [emailIds, phoneIds] = await Promise.all ([ | |
| Promise.all(contact.emails.map(email => db.emails.put(email))), | |
| Promise.all(contact.phones.map(phone => db.phones.put(phone))) | |
| ]); | |
| // Was any email or phone number deleted from out navigation properties? | |
| // Delete any item in DB that reference us, but is not present | |
| // in our navigation properties: | |
| await Promise.all([ | |
| db.emails.where('contactId').equals(contact.id) // references us | |
| .and(email => emailIds.indexOf(email.id) === -1) // Not anymore in our array | |
| .delete(), | |
| db.phones.where('contactId').equals(contact.id) | |
| .and(phone => phoneIds.indexOf(phone.id) === -1) | |
| .delete() | |
| ]); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment