Home » Android » javascript – Actualize Database Data with Functions Cloud-Exceptionshub

javascript – Actualize Database Data with Functions Cloud-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I am developing an Android application and I have a problem that I cannot solve despite reading the tutorials on Inernet …

In my application, the user has a life bar (100 points) and I would like that every 60 seconds (for example) the life bar decreases by a certain value (Even when the user is logged out).
The data is registered in a Firebase database:

{
    "actualize": {
        "state" : true,
        "time" : 60000
            },
    "users": {
        "-M-gSECRUGQMUrBbJ8wF": {
            "healthBar": 100,
            "substractionPoint" : 1
            },
        "-M-gSEijB-lClfuKkMUh": {
            "healthBar": 75,
            "substractionPoint" : 1.5
            }
        }
}

So I want to use the Functions Cloud part of Firebase, but I can’t make a TypeScript code that suits me. Here is the diagram I would like:

//Data recovery from the database
actualiseState -> boolean
actualizeTime -> number

<idUser>/healthBar -> number
<idUser>/substractionPoint -> number

//A trigger ?
do {
<idUser>/healthBar = (<idUser>/healthBar) - <idUser>/substractionPoint

update value in database

sleep(actualizeTime)
}

while (state = true)

Thank you in advance for your help 😉 / Translated by Google Translate

How to&Answers:

I built this code but it doesn’t suit my expectations :

import * as functions from 'firebase-functions';

let actualiseState: boolean
let actualizeTime: number

export const vvalueActualize = functions.database
.ref('/actualize')
.onUpdate(async(change, context) => {

let afterData = change.after.val()

actualiseState = afterData.state
actualizeTime = afterData.time
})


export const onMessageUpdate = functions.database
.ref('/users/{userId}')
.onUpdate(async(change, context) => {

    if (actualiseState){

        await sleep(actualizeTime)

const afterData = change.after.val()

const healtBar = afterData.healtBar
const substractionPoint = afterData.substractionPoint

const newValueData = healtBar - substractionPoint

if (newValueData <= 0){
    return change.after.ref.update({valeur: 0})
}
else {
    return change.after.ref.update({valeur: newValueData})
}

}

})


function sleep(ms: number) {
    return new Promise(resolve => setTimeout(resolve, ms));
    }