DEV Community

Cover image for Atomic Increment/Decrement in FaunaDB
Karma
Karma

Posted on • Originally published at karmasakshi.Medium

Atomic Increment/Decrement in FaunaDB

I talk about how to atomically increment/decrement values in FaunaDB.

Credit

Original answer here: https://news.ycombinator.com/item?id=24618998.

Code

Suppose you have an article schema like so:

// Schema

Article {
  slug: string;
  likes: number;
}
Enter fullscreen mode Exit fullscreen mode

To atomically increment likes, you need to invoke Update() with two parameters:

  1. Document reference
  2. Part of the document to be updated

For the value of the key to be updated, invoke Add() with two parameters:

  1. Select() with the path to the key, to get the current value
  2. Value to increment/decrement by (1 in our case; pass -1 to decrement)
// Query

documentReference; // Assuming this is available
Update(
  documentReference,
  {
    data: {
      likes: Add(
        Select(['data', 'likes'], Get(documentReference)),
        1
      )
    }
  }
)
Enter fullscreen mode Exit fullscreen mode

In situations when the document reference is not known, and you’re obtaining it as an output of another function, call Update() in Lambda(). For example, suppose you have an Index allArticles with terms as data.slug in order to be able to find documents by slug. To atomically increment likes in all matched documents:

// Query

Map(
  Paginate(
    Match(
      Index('allArticles'),
      'article-about-faunadb'
    )
  ),
  Lambda(
    'X',
    Update(
      Var('X'),
      {
        data: {
          likes: Add(
            Select(['data', 'likes'], Get(Var('X'))),
            1
          )
        }
      }
    )
  )
)
Enter fullscreen mode Exit fullscreen mode

Cheers!

Top comments (0)