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
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.