Search code examples
couchbasecouchbase-litecouchbase-sync-gateway

Couchbase: Sync data with conditions


I am building chat application where mobile app user keeps data on his device. We try to sync only user-related data from the server to client( couchbase server to couchbase mobile ). But from mobile using swift all Bucket is stored from server to mobile internal db. My sync json is

{
  "interface": "192.168.0.68:4984",
  "adminInterface": "192.168.0.68:4985",
  "pretty": true,
  "log": ["*"],
  "databases": {
    "db": {
        "server": "http://192.168.0.68:8091",
        "bucket": "travel-sample",

        "username":"himanshu",
        "password":"123456",
        "users": {
            "himanshu": {
              "password": "123456",
              "admin_channels": [
                "*"
              ]
            }
          },
        "sync":`
            function (doc) {
                console.log("doc=================================================================>")
                channel (doc.channels);
            }
        `   
    }
}}

It is possible that server send only related data to mobile for sync.


Solution

  • This can be achieve using proper configuration of Channels for each user to define access and can restrict users.

    The sync function is allowed to grant users access to channels based on the contents of documents

    In this case when you create a document it's properties should indicate that a particular user has created/edited and based on that the sync function kicks in to get the replication going on.

    Create an array of tags based on document type a given user interested in to replicate on mobile and pass this in your sync function

    { 
      "tags" : [
        "fashion",
        "outing",
        "shopping"
       ]
    }
    

    and Sync function would be similar as

    function(doc) {
      channel(doc.tags);
    }
    

    ON a client end synchronize the relevant user content by using built in replication API , which set up the user's topic interest to pull relevant data. The replicator will then interact with the data from channels. Create a pull replication as in Objective-C code

    CBLReplication *pull = [database createPullReplication: url];
    pull.channels = @[@"outing",@"shopping"];
    [pull start];
    

    If we have not set the specific channel then probably all the data that exists will be pull down from Sync Gateway.