Work With Sync Functions

    +
    Provides an example configuration suitable for beginning to use sync functions

    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: databases.$db.sync property).

    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:

    
    {
      "log": ["*"],
      "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);
            }
          }`
        }
      }
    }

    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 shared bucket access 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. 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 data base (see: databases.$db.sync property). )
    Next Steps
    Do more:
    • Import Filters: To use Sync Gateway on clusters with a large amount of data you can configure an import filter (see: Configure import filter).

    Dive Deeper

    See our blog, including Using Sync Gateway Channels