How do I add a check constraint for write operations?

write has two arguments - one for the original document data and one for the document data to be written.

But I can only define one argument instead of two in check constraints.

What I want to accomplish:

Collection.byName("Question")!.update({
  constraints: [
    {
      check: {
        name: "isOwner",
        body: `(newDoc, originalDoc) => {
          (newDoc.owner == Query.identity() && originalDoc == false) 
          || originalDoc.owner == Query.identity()
        }`
      }
    }
  ]
})
  1. The document can be created if the query identity is the same as the .owner in the new document to be created
  2. The document can be updated if the query identity is the same as the owner in the original document

Hi Mike. It looks like you are confusing the signatures for Role predicates and check constraints, which are two complete different topics.

Permission predicates

The image at the top appears to come from the Role document definition.

If you want to define a permission predicate for write operations, then the predicate indeed takes two arguments, the “old” and the “new” state of the document.

Check constraint

Check constraints are unrelated to permissions. You may be authorized to write to a document, but a check constraint applies a custom validation on the input. The only argument for the check constraint body is the new document.

Some examples are provided in the docs.

constraints: [
    {
      check: {
        name: "hasFunds",
        body: "(.balance >=0)"
      }
    }
  ]

The body definition .balance >= 0 is shorthand for the lambda (doc) => doc.balance >= 0, where it’s easier to see that exactly one argument was provided.

The documentation (FQL and FSL) indicate the signature accepts ZERO arguments, and that is incorrect. I’m filing that for our docs team.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.