Write custom logic with UDFs
Fauna supports user-defined functions (UDFs) for encapsulating business logic as manageable and maintainable resources. UDFs are equivalent to SQL stored procedures.
A UDF is an anonymous function with the same calling syntax as the JavaScript arrow function expression.
UDFs support variadic parameters using the …
syntax. See
Variadic
functions.
You define UDFs in Fauna Schema Language (FSL) as a schema. You manage schemas using the Fauna Dashboard or the Fauna CLI.
The examples in this tutorial use the Fauna Dashboard and Fauna’s demo data.
Create a UDF and call it
This example UDF calculates the circumference of a circle.
-
In the Dashboard, open the Demo database and add the following
getCircumference()
function:function getCircumference(radius) { 2 * Math.PI * radius }
-
Call the UDF by its name, passing a parameter:
75.39822368615503
-
To view the UDFs for the database, call
Function.all()
:{ data: [ { name: "inventory", coll: Function, ts: Time("2099-04-09T17:39:57.983Z"), role: "server", body: <<-END (name) => { Product.byName(name) { name: .name, description: .description, quantity: .quantity } } END }, ... { name: "getCircumference", coll: Function, ts: Time("2099-04-09T17:39:57.983Z"), body: "radius => 2 * Math.PI * radius" } ] }
Use UDFs to store a query
You can also use UDFs to store common queries for reuse.
The following example uses the Product
collection from Fauna’s
demo data.
-
In the Dashboard, create a
productsByNameAndQuantity()
function that:-
Accepts the
name
andquantity
parameters. -
Uses the
Product
collection’sbyName
index to:-
Search for products with the provided
name
. -
Filter matching products to those with a quantity less than or equal to the provided
quantity
.
-
-
Returns the
name
,description
, andquantity
of matching products.
function productsByNameAndQuantity(name, quantity) { Product.byName(name, { from: quantity }) { name: .name, description: .description, quantity: .quantity } }
-
-
Call the function with a
name
oflimes
and aquantity
of50
:productsByNameAndQuantity("limes", 50)
The query returns products named
limes
that have aquantity
of50
or less:{ data: [ { name: "limes", description: "Organic, 16 oz bag", quantity: 45 }, { name: "limes", description: "Conventional, 16 oz bag", quantity: 22 } ] }
Delete a UDF
To delete a function, remove its schema using the Fauna Dashboard or Fauna CLI. With the CLI:
-
Delete the
.fsl
file for the function schema from your schema directory. -
Run
fauna schema push
to push the updated schema directory to Fauna. This deletes the function.
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!