Triggers
You can have one query trigger another query.
Triggered queries can bypass access control rules, so this comes in handy when updating one collection owned by a user and another collection not owned by the same person.
For example, a user likes a tweet, which triggers an increment of the like count that the user doesn't have access to update.
You can think of it as an equivalent to Firestore Triggers. It's an essential component when building apps.
Add Triggers
key
: name of the triggeron
: create | update | deletefn
: FPJSON logicfields
: fields to match (match anything if not specified)match
: all | any | none (default toany
)
If fields
is specified, the fn
is triggered only the fields are changed with the specified match
type.
FPJSON will get an object containing the data before
and after
the change.
let vars = { before, after, id, dir, doc, owner, signer, signer23, ts }
A trigger to increment the like count.
const { expect } = require("chai")
const trigger = {
key: "inc_likes",
on: "create",
fn: [["update", [{ likes: { _$: ["inc"] }, "notes", "$after.object"]]],
fields: [ "object" ]
match: "any"
}
await db.addTrigger(trigger, "likes")
// like a note
await db.set("add:like", { object: noteId }, "likes")
// likes has been incremented
assert.equal((await db.get("notes", noteId)).likes, 1)
Get Triggers
const triggers = (await db.stat("likes")).triggers ?? {}
Remove Triggers
Specify the trigger key to remove.
await db.removeTrigger({ key: "inc_likes" }, "likes")