Navigation

JSON Expressions

Overview

A JSON expression is a dynamic EJSON document that you use to define service rules in Stitch. Stitch evaluates expressions to boolean values and uses the result to determine whether or not to allow specific actions.

Expression Syntax

JSON Expressions use expression variables to represent dynamic, runtime information, such as the logged in user that called an action (%%user) or the arguments that were passed the action (%%args). Each field name in an expression must be an expansion.

Expressions documents have the following general format:

{
  <field1>: <value1|expression1>,
  <field2>: <value2|expression2>,
  ...
}

Evaluation

Stitch evaluates expressions by first replacing expansions with their runtime values and then evaluating each field of the expanded expression document to a boolean expression. If all fields in an expression evaluate to true, the expression also evaluates to true.

Expression fields evaluate based on the following rules:

  • If an expanded field name matches its value, it evaluates to true.
  • If a field’s value is an embedded expression, it evaluates to the same value as the embedded expression. See embedded expressions.

Note

If a rule does not explicitly use the %%args or %%root expansion, expression field names default to checking for arguments or document fields of the same name. For example, the expression { "url": "https://www.example.com" } defaults to evaluating the value against %%args.url in a service rule and %%root.url in a MongoDB rule.

Expression Composition

You can combine multiple expressions to enforce complex and nuanced conditions. There are two ways to compose expressions:

Embedded Expressions

You can embed multiple expression documents in the fields of another expression document to handle complex evaluation logic. Stitch evaluates expressions depth-first, i.e. it evaluates the most-deeply embedded documents first and works back to the root-level fields.

Example

This expression evaluates to true only if the number provided as the someNumber argument falls in a specific range.

{
  "%%args.someNumber": {
     "%and": [
        { "$gt": 0 },
        { "$lte": 42 }
     ]
  }
}

Multi-Field Expressions

Expressions with multiple fields are analagous to an AND operation on the evaluated value of each field.

Example

This expression evaluates to true only if both the url argument was provided and the body.userId argument matches the id of the user that called the action.

{
  "%%args.url": { "%exists": true },
  "%%args.body.userId": "%%user.id"
}