Call a Function
On this page
Overview
You can call a function from other parts of your Realm app, from a connected client application, or with Realm CLI.
The examples in this section demonstrate calling a simple function named
sum
that takes two arguments, adds them, and returns the result:
// sum: adds two numbers exports = function(a, b) { return a + b; };
Call from A Function, Trigger, or HTTP Endpoint
You can call a function from another function, including HTTPS endpoints
and triggers, by accessing function context
with the context.functions
interface:
// difference: subtracts b from a using the sum function exports = function(a, b) { return context.functions.execute("sum", a, -1 * b); };
Call from a JSON Expression
You can call a function from a rule expression, including
service rules, by using the %function
operator:
{ "numGamesPlayed": { "%function": { "name": "sum", "arguments": [ "%%root.numWins", "%%root.numLosses" ] } } }
Call from Realm CLI
To call a function with Realm CLI, run realm-cli
function run
and specify the function name and any arguments. The command
returns the function result as EJSON as well as any log or error messages.
User Functions
To call a function in the context of a specific user, include their User
ID in the --user
argument.
realm-cli function run \ --function=sum \ --user=61a50d82532cbd0de95c7c89 \ --args=1 --args=2
System Functions
To call a function in the system context, do
not include the --user
argument. System functions bypass all rules
and do not enforce or validate schemas.
realm-cli function run \ --function=sum \ --args=1 --args=2
Call from a Client Application
Make sure to sanitize client data to protect against code injection when using Functions.
You can call a function from client applications that are connected with a Client SDK or over the wire protocol.