The Sync Function is one of the fundamental components of Sync Gateway: its main responsibility is to define which user has access to which documents. In this screencast, you’ll learn how to use the public channel (also known as the ! channel) to synchronize documents to users that haven’t logged into your app yet. This feature is particularly useful when designing the on boarding journey with dynamic data that can be changed on the backend and pulled automatically when the user starts the app for the first time. We’ll consider a note taking application and explore the following:
- Use the public channel to insert the Getting Started note, you can think of it as the tutorial note when the user starts the app for the first time
- Map the note created by a registered user to a channel that is only accessible by that user
- Enforce write permissions with the requireUser method
- Test the Sync Function with curl commands
Find the code for this lesson
You can find the Sync Gateway config file below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
{ "log": ["CRUD"], "databases": { "notes": { "server": "walrus:", "users": { "GUEST": {"disabled": false}, "william": {"password": "pass"}, "admin": {"password": "pass"} }, "sync": ` function sync(doc, oldDoc) { switch(doc.security) { case "public": requireUser("admin"); channel("!"); break; default: requireUser(doc.user_name); channel(doc._id); access(doc.user_name, doc._id); } } ` } } } |
And the curl commands to test the Sync Function:
- Persist a Public Note via the Admin API
123curl -X POST http://localhost:4985/notes/-H "Content-Type: application/json"-d '{"security": "public", "title": "Getting Started"}' - User Authentication
123curl -vX POST http://localhost:4984/notes/_session-H "Content-Type: application/json"-d '{"name": "william", "password": "pass"}' - Persist a User Note
1234curl -X POST http://localhost:4984/notes/-H "Content-Type: application/json"-H "Cookie: SyncGatewaySession=PASTE_COOKIE_VALUE"-d '{"user_name": "william", "title": "Overview of the user journey"}'