Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment value in faunadb? Using javascript and serverside functions

I have a value in my faunadb database that i want to increase by one when clicking a button.
I am not sure how to do that


i tried it with this:

const change = (data) => {
  return fetch(`/.netlify/functions/todos-update`, {
    body: JSON.stringify(data),
    method: 'POST'
  }).then(response => {
    return response.json()
  })
}


and triggered it with this

var dataa = document.getElementById('amount').innerHTML
change(("value: " + dataa))

my serverside code is this:

exports.handler = (event, context, callback) => {
  const data = JSON.parse(event.body)
  const id = "236323245287014920"
  console.log(`Function 'todo-update' invoked. update id: ${id}`)
  return client.query(q.Update(q.Ref(`classes/nappi/${id}`), {data}))
    .then((response) => {
      console.log('success', response)
      return callback(null, {
        statusCode: 200,
        body: JSON.stringify(response)
      })
    }).catch((error) => {
      console.log('error', error)
      return callback(null, {
        statusCode: 400,
        body: JSON.stringify(error)
      })
    })
}

i expected this to increment my value in the database by 1 but in reality i get an error that looks like this: POST https://nappula.tk/.netlify/functions/todos-update 400 (Bad Request)
I am not sure where i went wrong

like image 716
Skelly Avatar asked Jul 04 '19 21:07

Skelly


People also ask

How to get the increment value from a function in JavaScript?

var increment = (function (n) { return function () { n += 1; return n; } } (0)); // -1 if you want the first increment to return 0 console.log (increment ()); console.log (increment ()); console.log (increment ()); Show activity on this post. You need to declare n outside of the function.

How do I set up a serverless version of FaunaDB?

To get your serverless faunaDB up and running you will need to do these things: Easy, let's start! Using FaunaDB's console. Create a new test database and pre-populate it with data. Next, let's get an API key for our new test database. Using FaunaDB's console. Create a new server API key. Here is a quick gif that explains how to do that:

How to increment a value twice when you run a function?

Then we define function f that increments count by 1. Then we call f twice. As a result, count is 2 according to the console log. To increment value each time when you run function with JavaScript, we can create a variable outside the function and increment that when the function is run.

How to increment a value in a map in Java?

To increment a value in a Map, use the set () method on the Map, passing it the name of the key and the value as parameters, e.g. map.set ('num', map.get ('num') + 1 || 1);. If the key exists in the Map, the value gets incremented, and if it doesn't, it gets initialized to 1.


1 Answers

For non trivial apps you should not rely on going back and forth to JavaScript land (or any other non-DB level language) to increment. It is not safe because someone else can increment at basically the same time and then you might overwrite their increment if your network happens to be slower. Only the database will be able to know whether to lock or not in this situation.

Here is an example, if the initial click count of a topic is 1, then at the exact same time you and I both increment that count then the database must know that the actual count should be 3 and not 2. You should have an increment function in your FaunaDB to ensure that the it can block as needed to ensure that the correct clickCount is applied.

Let's assume you have a collection called topics with a few documents that look like this:

topic document #id 254119747652682260

{ slug: "dev", clickCount: 1 }

topic document #id 254119747652122323

{ slug: "design", clickCount: 1 }

So how can you safely increment the clickedCount field from 1 to 2, on a document with id of 254119747652682260, in the topics collection?

Update(
    Ref(
        Collection('topics'),
        '254119747652682260'
    ),
    { 
        data: { 
            clickCount: Add(
                Select(
                    ['data','clickCount'],
                    Get(
                        Ref(
                            Collection('topics'),
                            '254119747652682260'
                        )
                    )
                ),
                1
            )
        }
    }
)

Hopefully that helps.

like image 68
JimTheDev Avatar answered Oct 11 '22 02:10

JimTheDev