Skip to content

Instantly share code, notes, and snippets.

@kurtroberts
Created September 10, 2020 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurtroberts/0d206a354ea4bfc2ad38f7c33fb4f604 to your computer and use it in GitHub Desktop.
Save kurtroberts/0d206a354ea4bfc2ad38f7c33fb4f604 to your computer and use it in GitHub Desktop.
Amplify Datastore - Control when Sync Starts
/******
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