-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync-function.js
More file actions
39 lines (32 loc) · 1.08 KB
/
sync-function.js
File metadata and controls
39 lines (32 loc) · 1.08 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
// Sync Gateway Sync Function skeleton
// Assigned to an App Endpoint (Sync Gateway database config)
// Called for every document write — controls access, routing, and validation.
function sync(doc, oldDoc) {
// --- Validation ---
if (!doc.type) {
throw({ forbidden: "Document must have a 'type' field" });
}
// Prevent changing document type
if (oldDoc && oldDoc.type !== doc.type) {
throw({ forbidden: "Cannot change document type" });
}
// --- Channel routing ---
// Route to a user-specific channel
if (doc.userId) {
channel("user." + doc.userId);
}
// Route to a shared channel by type
channel(doc.type);
// --- Access control ---
// Grant the owning user read/write access to their channel
if (doc.userId) {
access(doc.userId, "user." + doc.userId);
}
// Grant admins access to all channels
access("role:admin", "*");
// --- Role assignment ---
// Assign roles based on document content
if (doc.type === "user" && doc.role) {
role(doc.userId, "role:" + doc.role);
}
}