Create a function

Creating and updating a function requires:

Problem

You need to create a user-defined function in the current database.

Solution

Use the CreateFunction function:

Let’s create a function to allow authors to create new blog posts. We’ll set it up to allow the author to provide a title and body. This way authors are constrained by what data they can store on a post document.

try
{
    Value result = await client.Query(
        CreateFunction(
            Obj(
                "name", "create_post",
                "body", Query(
                    Lambda(
                        Arr("title", "body"),
                        Create(
                            Collection("posts"),
                            Obj(
                                "data", Obj(
                                    "title", Var("title"),
                                    "body", Var("body")
                                )
                            )
                        )
                    )
                )
            )
        )
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
ObjectV(ref: RefV(id = "create_post", collection = RefV(id = "functions")),ts: LongV(1622572599150000),name: StringV(create_post),body: QueryV(System.Collections.Generic.Dictionary`2[System.String,FaunaDB.Query.Expr]))
result, err := client.Query(
	f.CreateFunction(
		f.Obj{
			"name": "create_post",
			"body": f.Query(
				f.Lambda(
					f.Arr{"title", "body"},
					f.Create(
						f.Collection("posts"),
						f.Obj{
							"data": f.Obj{
								"title": f.Var("title"),
								"body": f.Var("body"),
							},
						},
					),
				)),
		}))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
map[body:{[123 34 97 112 105 95 118 101 114 115 105 111 110 34 58 34 52 34 44 34 108 97 109 98 100 97 34 58 91 34 116 105 116 108 101 34 44 34 98 111 100 121 34 93 44 34 101 120 112 114 34 58 123 34 99 114 101 97 116 101 34 58 123 34 99 111 108 108 101 99 116 105 111 110 34 58 34 112 111 115 116 115 34 125 44 34 112 97 114 97 109 115 34 58 123 34 111 98 106 101 99 116 34 58 123 34 100 97 116 97 34 58 123 34 111 98 106 101 99 116 34 58 123 34 98 111 100 121 34 58 123 34 118 97 114 34 58 34 98 111 100 121 34 125 44 34 116 105 116 108 101 34 58 123 34 118 97 114 34 58 34 116 105 116 108 101 34 125 125 125 125 125 125 125]} name:create_post ref:{create_post 0xc000109ec0 0xc000109ec0 <nil>} ts:1622572622400000]
System.out.println(
    client.query(
        CreateFunction(
            Obj(
                "name", Value("create_post"),
                "body", Query(
                    Lambda(
                        Arr(Value("title"), Value("body")),
                        Create(
                            Collection("posts"),
                            Obj(
                                "data", Obj(
                                    "title", Var("title"),
                                    "body", Var("body")
                                )
                            )
                        )
                    )
                )
            )
        )
    ).get());
{ref: ref(id = "create_post", collection = ref(id = "functions")), ts: 1622572634070000, name: "create_post", body: QueryV({api_version=4, lambda=[title, body], expr={create={collection=posts}, params={object={data={object={title={var=title}, body={var=body}}}}}}})}
client.query(
  q.CreateFunction({
    name: 'create_post',
    body: q.Query(
      q.Lambda(
        ['title', 'body'],
        q.Create(
          q.Collection('posts'),
          {
            data: {
              title: q.Var('title'),
              body: q.Var('body'),
            },
          },
        ),
      )
    ),
  })
)
.then((ret) => console.log(ret))
.catch((err) => console.error('Error: %s', err))
{
  ref: Function("create_post"),
  ts: 1622572663690000,
  name: 'create_post',
  body: Query(Lambda(["title", "body"], Create(Collection("posts"), {"data": {"title": Var("title"), "body": Var("body")}})))
}
result = client.query(
  q.create_function({
    "name": "create_post",
    "body": q.query(
      q.lambda_(
        ["title", "body"],
        q.create(
          q.collection("posts"),
          {
            "data": {
              "title": q.var("title"),
              "body": q.var("body")
            }
          }
        )
      )
    )
  })
)
print(result)
{'ref': Ref(id=create_post, collection=Ref(id=functions)), 'ts': 1622572667700000, 'name': 'create_post', 'body': Query({'api_version': '4', 'lambda': ['title', 'body'], 'expr': {'create': {'collection': 'posts'}, 'params': {'object': {'data': {'object': {'title': {'var': 'title'}, 'body': {'var': 'body'}}}}}}})}
try {
  println(Await.result(
    client.query(
      CreateFunction(
        Obj(
          "name" -> "create_post",
          "body" -> Query(
            Lambda(
              Arr("title", "body"),
              Create(
                Collection("posts"),
                Obj(
                  "data" -> Obj(
                    "title" -> Var("title"),
                    "body" -> Var("body")
                  )
                )
              )
            )
          )
        )
      )
    ),
    5.seconds
  ))
} catch {
  case unknown: Throwable => println("Error: " + unknown.getMessage())
}
{ref: ref(id = "create_post", collection = ref(id = "functions")), ts: 1622572699080000, name: "create_post", body: {api_version: "4", lambda: ["title", "body"], expr: {create: {collection: "posts"}, params: {object: {data: {object: {title: {var: "title"}, body: {var: "body"}}}}}}}}
CreateFunction({
  name: 'create_post',
  body: Query(
    Lambda(
      ['title', 'body'],
      Create(
        Collection('posts'),
        {
          data: {
            title: Var('title'),
            body: Var('body'),
          },
        },
      ),
    )
  ),
})
{
  ref: Function("create_post"),
  ts: 1624310578910000,
  name: 'create_post',
  body: Query(Lambda(["title", "body"], Create(Collection("posts"), {data: {title: Var("title"), body: Var("body")}})))
}

Was this article helpful?

We're sorry to hear that.
Tell us how we can improve!
Visit Fauna's Discourse forums or email docs@fauna.com

Thank you for your feedback!