Synchronization - Syonet/model GitHub Wiki
Model is built with synchronization in mind. We cover a few common use cases for offline usage, which you can read about in this page.
Manipulating documents while offline
Everytime you trigger some request that will update the server - that is, an POST
, PATCH
or DELETE
-, Model will keep record of the configuration of your request to try it again later if you're offline.
You'll be able to continue using the documents you manipulated, but note that they'll receive an temporary ID if they were never persisted before:
{
"_id": "$$temp1",
"foo": "barbaz"
}
By default, Model will retry every request every minute and when the online
event happens in the DOM.
Changing the synchronization process
You're able to reschedule the synchronization process by using the modelSync
service:
// Will sync every 10 minutes
modelSync.schedule( 10 * 60 * 1000 );
Or, for some reason, you're interested in disabling the synchronization:
modelSync.schedule.cancel();
Referencing documents created while offline
Suppose you created a new document in the project
collection while you were offline. You'll want to add users to that project, right? But what does guarantee that the project will be created before the user is added?
Model will wait every temporary ID used in a request to be resolved before triggering your request. So the following calls will be stacked, instead of triggered in parallel when you get back online:
model( "project" ).create({
name: "Foobar Project"
}).then(function ( project ) {
// project._id looks like $$temp123, but the request made will not be POST /project/$$temp123/user
return model( "project" ).id( project._id ).model( "user" ).create({
username: "john.doe",
role: "reporter"
});
});
Failed synchronization requests
If you previously created an document and the server rejects it for some reason when you're back online, these documents will be removed from their caches. Additionally, an error
event will be emitted from the modelSync
service:
modelSync.on( "error", function ( event, error, row ) {
// error is in the usual format { status, data }
console.log( "Server response: " + err.status + " - " + err.data );
// row is the PouchDB registry for the sync object that failed
console.log({
id: row.id,
url: row.doc.model,
method: row.doc.method,
data: row.doc.data,
options: row.doc.options
});
});