Created
September 10, 2020 17:45
-
-
Save kurtroberts/0d206a354ea4bfc2ad38f7c33fb4f604 to your computer and use it in GitHub Desktop.
Amplify Datastore - Control when Sync Starts
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
/****** | |
Amplify's DataStore is useful, but it is very, very immature and has some | |
incredibly naive implementation choices. One of those is that it will | |
perform synchronization on the first call to query, regardless of a call | |
to start. | |
This is an issue, because most non-trivial applications will require a | |
login so that the app can load appropriate content for the user in question. | |
This decorates the basic datastore object with a wrapper that defers any calls | |
to query until after the datastore is started manually and ready, and will | |
throw exceptions for calls to save and delete if the DataStore hasn't been | |
started yet. It makes use of DataStore's undocumented Hub channel, which | |
raises a ready event when the initial synchronization is complete. | |
*/ | |
import { DataStore, Hub } from 'aws-amplify'; | |
let started = false, | |
deferredQuery = (model, criteria, options) => { | |
console.log('deferred query for ', model); | |
return new Promise((resolve, reject) => { | |
Hub.listen('datastore', (data) => { | |
const { payload } = data; | |
if (payload.event == "ready") { | |
console.log('releasing deferred query for ', model); | |
resolve(DataStore.query(model, criteria, options)); | |
} | |
}); | |
}); | |
}; | |
export default { | |
start: () => { | |
started = true; | |
console.log('Starting datastore...'); | |
return DataStore.start(); | |
}, | |
query: (model, criteria, options) => { | |
if (started == true) { | |
return DataStore.query(model, criteria, options); | |
} else { | |
return deferredQuery(model, criteria, options); | |
} | |
}, | |
save: (object) => { | |
if (started == true) { | |
return DataStore.save(object); | |
} else { | |
throw "Datastore not initialized."; | |
} | |
} , | |
delete: (object, predicates) => { | |
if (started == true) { | |
DataStore.delete(object, predicates); | |
} else { | |
throw "Datastore not initialized."; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment