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 (opens in a new tab). It's an essential component when building apps.

Add Triggers

  • key : name of the trigger
  • on : create | update | delete
  • func : FPJSON logic

FPJSON (opens in a new tab) will get an object containing the data before and after the change.

{
  data: { before, after, id, setter }
}

A trigger to increment the like count.

const { expect } = require("chai")
 
const trigger = {
  key: "inc-count",
  on: "create",
  func: [["upsert", [{ count: db.inc(1) }, "like-counts", { var: "data.id" }]]]
}
await db.addTrigger(trigger, "likes")
 
// like tweet
await db.set({ data: Date.now(), user: "Bob" }, "likes", "abc")
 
// like-count has been incremented
expect((await db.get("like-counts", "abc")).count).to.equal(1)

Remove Triggers

Specify the trigger key to remove.

await db.removeTrigger("inc-count", "like-counts")