Function schema
Learn: User-defined functions |
---|
Defines a user-defined function (UDF).
Syntax
[@role(<roleName>)]
[@alias(<aliasId>]
function <functionName> (<parameter>: <parameterType>): <returnType> {
<functionBody>
}
Annotations
This is the role to use when the UDF is called. This is typically used for privilege escalation when current privileges would otherwise be too restrictive. A function must declare a built-in role to be able to view logs.
The role can be set only by users with a privileged role, such as admin
,
server
, or a user-defined role that grants write privilege for
Functions.
Use role carefully. Setting the role privilege gives the function permission to create, change, and remove documents when invoked by calling the function. A UDF can change a role to change function privileges.
Examples
Basic example
// Defines the `MyFunction()` function.
// The function adds two to the provided number.
function MyFunction(x: Number): Number {
x + 2
}
Role annotation
The following UDF includes the @role
annotation:
// Defines the `inventory()` function.
// Runs with the built-in `server-readonly` role's privileges.
@role(server)
function inventory(name) {
Product.byName(name) {
name,
description,
quantity
}
}
Pass collection as an argument
The following example passes a collection name as an argument. Use
Collection()
to
dynamically specify collection names in a query:
// Accepts a collection name as an argument.
function getPriceLowtoHigh(collection) {
// Uses `Collection()` to dynamically specify
// the collection name.
Collection(collection).sortedByPriceLowToHigh() {
price,
name,
description
}
}
The following query calls the function:
// Calls the `getPriceLowtoHigh()` UDF with
// a `Product` collection argument.
getPriceLowtoHigh("Product")
Is this article helpful?
Tell Fauna how the article can be improved:
Visit Fauna's forums
or email docs@fauna.com
Thank you for your feedback!