Skip to content

Instantly share code, notes, and snippets.

@rts-rob
Last active April 1, 2021 15:30
Show Gist options
  • Save rts-rob/3ed8f5064e9e296cd9707a3f12b1a826 to your computer and use it in GitHub Desktop.
Save rts-rob/3ed8f5064e9e296cd9707a3f12b1a826 to your computer and use it in GitHub Desktop.
Increment a counter using Fauna and GraphQL

Increment a counter using Fauna and GraphQL

Step by step instructions to implement this solution by Luigi Servini in the Fauna forums.

  1. Save schema.graphql from this gist on your machine.
  2. Create a new database in the Fauna dashboard.
  3. On the GraphQL tab, choose Import Schema then upload schema.graphql.
  4. On the Collections tab, select the Counter collection and choose New Document to create a new document. Copy and paste the contents of counter.json then choose Save.
  5. Copy the ID of the new document, e.g., 294683317926625795.
  6. On the Functions tab, select the user-defined function (UDF) increment_counter. Copy the code from increment_counter.fql and paste it into Function Body. Replace <document_id> with the document ID you copied in the previous step and choose Save.
  7. Return to the GraphQL tab, copy the GraphQL query from query.graphql, and paste the query in the GraphQL playground. When you run your query you should receive:
{
  "data": {
    "nextCounter": {
      "counter": 1
    }
  }
}
{
"counter": 0
}
Query(
Lambda(
[],
Let(
{
counter: Get(Ref(Collection("Counter"), "<document_id>")),
counterRef: Select(["ref"], Var("counter")),
counterValue: Select(["data", "counter"], Var("counter"))
},
Update(Var("counterRef"), {
data: { counter: Add(Var("counterValue"), 1) }
})
)
)
)
{
nextCounter {
counter
}
}
type Counter {
counter: Int!
}
type Query {
nextCounter: Counter! @resolver(name: "increment_counter")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment