Sync Functions

    +

    Description — Introducing sync functions and how to use them
    Abstract — This content introduces the sync function, provides a simple example configuration suitable for those getting started using sync functions.
    Related Content — Configuration Details | Admin REST API

    Sync Function Basics

    The Sync Function is a JavaScript function whose source code is stored in the Sync Gateway’s database configuration file. You can learn more about this property ($db.sync) in the Configuration Schema Reference — see: sync.

    The sync function is called every time a new revision/update is made to a document, and the changes to channels and access made by the sync function are tied to that revision. If the document is later updated, the sync function will be called again on the new revision, and the new channel assignments and user/channel access replace the ones from the first call.

    It can do the following things:

    For simple applications it might be the only server-side code you need to write. For more complex applications it is still a primary touchpoint for managing data routing and access control.

    Configuration

    Add the sync function defined below into your sync-gateway-config.json:

    //
    {
      //  ... may be preceded by additional configuration data as required by the user ...
      "databases": {
        "getting-started-db": {
          "server": "http://localhost:8091",
          "bucket": "getting-started-bucket",
          "username": "sync_gateway", (1)
          "password": "password", (2)
          "enable_shared_bucket_access": true, (3)
          "import_docs": true,
          "num_index_replicas": 0, (4)
          "users": {
            "GUEST": { "disabled": false, "admin_channels": ["*"] },
          },
          "sync": `function (doc, oldDoc) { (5)
            if (doc.sdk) {
              channel(doc.sdk);
            }
            }`,
            //  ... may be followed by additional configuration data as required by the user ...
        }
      }
    }
    //

    Configuration properties:

    1 The user’s username that you created on the Couchbase Server Admin Console.
    2 The user’s password that you created on the Couchbase Server Admin Console.
    3 The Mobile-Server Replication feature allows Couchbase Server SDKs to also perform operations on this bucket.
    4 num_index_replicas is the number of index replicas stored in Couchbase Server, introduced with GSI/N1QL indexing — see Indexing. If you’re running a single Couchbase Server node for development purposes the num_index_replicas must be set to 0.
    5 The sync function — a javascript function enclosed in backticks, which is actioned every time a new document, document revision or deletion is made to a database — see the: databases.$db.sync property.