Function schema

Learn: User-defined functions

Defines a user-defined function (UDF).

Syntax

[@role(<roleName>)]
[@alias(<aliasId>]
function <functionName> (<parameter>: <parameterType>): <returnType> {
  <functionBody>
}

Name

functionName String Required

Unique name of the UDF. The name is case insensitive and can’t be a reserved word.

Properties

Parameter Type Required Description

parameter

String

Yes

functionBody parameter

parameterType

String

Yes

parameter type

returnType

String

Yes

functionBody return type

functionBody

String

Yes

FQL block.

Annotations

roleName String

The optional @role annotation associates a Role named roleName with the function. The Role can be a user-defined role or one of the following built-in roles:

  • admin

  • server

  • server-readonly

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.

aliasId String or Identifier

The optional @alias annotation defines a second identifier for the function. The aliasId can be a String, "Foo", or an identifier, Foo.

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!