GraphQL counter
Problem
You want to increment a counter via a GraphQL query.
Fauna provides consistent results that are globally replicated. High-volume counter updates to a single document (as shown in this solution) create contention that can slow down your queries. We recommend alternatives such as:
|
Solution
There are several steps:
-
Update your GraphQL schema to include:
graphqlCopied!type Counter { counter: Int! } type Query { nextCounter: Counter! @resolver(name: "increment_counter") }
This involves editing the GraphQL schema definition, wherever you have stored it, and then uploading the new schema in the Fauna Dashboard.
-
Create a UDF to perform the counter increment:
{ ref: Function("increment_counter"), ts: 1626466930320000, name: 'increment_counter', body: Query(Lambda([], Let({"counterRef": Ref(Collection("Counter"), "1"), "counter": Get(Var("counterRef")), "counterValue": Select(["data", "counter"], Var("counter"))}, Update(Var("counterRef"), {"data": {"counter": Add(Var("counterValue"), 1)}})))) }
-
Create the required
Counter
document:{ ref: Ref(Collection("Counter"), "1"), ts: 1626466931300000, data: { counter: 0 } }
Here, we have set the initial counter value to
0
. -
Run a GraphQL query to increment the counter:
graphqlCopied!{ nextCounter { counter } }
You should see the result:
{ "data": { "nextCounter": { "counter": 1 } } }
-
You can also increment the counter in FQL queries:
{ ref: Ref(Collection("Counter"), "1"), ts: 1626466932180000, data: { counter: 1 } }
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!