"Upsert" FQL example not working

Functions are Documents, too! So similar to how you can “upsert” a Document, you can upsert a Function.

If you’re using JS, you can create a CreateOrUpdateFunction helper

const CreateOrUpdateFunction = (params) => q.Let(
  { 
    name: Select("name", params),
    params
  },
  q.If(
    q.Exists(q.Function(q.Var("name"))),
    q.Update(q.Function(q.Var("name")), q.Var("params")),
    q.CreateFunction(q.Var("params"))
  ),
)

The Let here helps to reduce how big the final query is. Otherwise, we would duplicate the entire set of params for both the create case as well as the update case.

Use it as a replacement for CreateFunction

    await faunadbClient.query(
      CreateOrUpdateFunction({
        name: 'upsert',
        body: q.Query(
          q.Lambda(
            ['ref', 'data'],
            q.If(
              q.Exists(q.Var('ref')),
              q.Update(q.Var('ref'), q.Var('data')),
              q.Create(q.Var('ref'), q.Var('data'))
            )
          )
        )
      })
    )

You can create similar helpers for CreateOrUpdateDatabase, CreateOrUpdateCollection and CreateOrUpdateRoles. You can do so with Indexes as well, but it would have to have extra validation, since you cannot edit terms or values once an Index is created.

2 Likes