Change document properties from Sync Gateway function

We’re currently building an application that is not guaranteed to always have an internet connection and thus our Mobile application might take quite a while before they start syncing the data to our server.

Let’s assume this scenario for our data setup:
Data level 1
Data level 2
Data level 3

Data level 1 is not mandatory
Data level 2 has an optional parent (Data level 1)
Data level 3 has a mandatory parent (Data level 2)

It’s possible to delete data at any level from our web application. Deleting is a soft delete, so data can potentially be restored at a later stage.
If Data level 1 gets deleted: all underlying data can also be deleted or the direct underlying children can be orphaned
If data level 2 or lower gets deleted: all underlying data is deleted (as parent are mandatory from that level onwards)

The current scenario is possible in our setup:
Data structure is setup and synced to Mobile client. Mobile client goes offline and does not sync until later in the scenario.
Data level 1 gets deleted from the web application, setting children either as deleted (deleted_on property set) or orphaned (parent_id set to null), depending on what is selected, doesn’t make a lot of difference for the scenario
When the Mobile client now changed one of the children from Data level 1 (so Data level 2) and tries to sync, it will attempt to ‘undelete’ or ‘unorphan’ the Data level 2 document, as it does not know about the new state of the document.

We can check in the Sync Gateway function if the parent_id or deleted_on was changed, but we cannot update the new incoming document to reflect these changes.
Question 1: Ideally we’d be able to take over these properties from the old document. I don’t seem to be able to do that, is this at all possible to achieve using the Sync Gateway function only?

We can trigger a webhook after the document changed, the webhook can then update the document as needed, however, we don’t have access to the old document in the webhooks. We also do not store what action was selected when deleting the Data levels
Question2: Is is possible to get access to the old document, so we can filter what webhook gets activated (and then call delete or orphan endpoint) or can the old document be send with the webhook to the configured endpoint?

1 Like

This is useful for me too, so bump

You can’t modify documents from the sync function. That’s not currently supported. IIRC you can try, and you won’t get an error, but the changes will not be persisted.

Sorry, I’m not clear on the old document question. The sync function receives a copy of both the new and old document. (You can leave it off, because, well, it’s Javascript, but the full signature is function (doc, oldDoc)).