javascriptnode.jsfirebasefirebase-realtime-databaseclaudiajs

Update realtime database in Firebase


I am creating a API which can update value from realtime database (Firebase). Using ClaudiaJS to create API. Basically, API will update the number of student of a class by year.

What I have done:

Realtime Database (Firebase)

class
 |__2015
 |    |__numberOfStudent: 50
 |__2016
      |__numberOfStudent: 60 

Export to JSON like this:

{
  "class": {
    "2015": {
      "numberOfStudent": 50
    },
    "2016": {
      "numberOfStudent": 60
    }
  }
}

Javascript file (ClaudiaJS):

var ApiBuilder = require('claudia-api-builder');
api = new ApiBuilder();
module.exports = api;

var admin = require("firebase-admin");

var serviceAccount = require("./xxxxxxx-firebase-adminsdk-nxxxxx.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://xxxxxx.firebaseio.com"
});

api.post('/addmore/{year}/{number}', function (request) {
    var database = admin.database().ref('class');

    //Params
    var year = request.pathParams.year;
    var number = request.pathParams.number;

    var ref = year + '/numberOfStudent'; // '2015/numberOfStudent'

    database.update({
        ref : parseInt(number) // "2015/numberOfStudent" : 60
    });

    return 'Update successfully';

});

When I run the api in Postman:

http://xxxxapi.com/addmore/2015/55

What happened: API replied 'Update successfully', but the database didn't get any update. It seems that the code database.update() doesn't work at all.

Any suggestion is very appreciated


Solution

  • The update call happens asynchronously, so currently the return happens before update completes.

    update returns a Promise, so try the following:

    return database.update({ref : parseInt(number)})
        .then(() => {
            // Each then() should return a value or throw
            return 'Update successful';
        })
        .catch(error => {
            // handle the error however you like
            console.error(error);
        });