Illep
Illep

Reputation: 16859

Firebase saving to database from cloud function API

I have wrote a Firebase cloud function that can be accessed via a REST API. The code is given below.

What I need to do is, when the user submits some values from the front end via the 'Web service URL' .

1.) I need these data to be saved in the Firebase-realtime database.

2.) I refereed to several tutorials on the net, and didn't understand what var ref = db.ref("server/saving-data/fireblog"); does in the following code.

const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')();
const os = require("os");
const path = require("path");
const cors = require("cors")({ origin: true });
var admin = require("firebase-admin");

var serviceAccount = require("./My-Service.json");
// Initialize the app with a service account, granting admin privileges
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://my-xx0xx.firebaseio.com/"
});

// As an admin, the app has access to read and write all data, regardless of Security Rules
var db = admin.database();
var ref = db.ref("server/saving-data/fireblog");


exports.uploadFile = functions.https.onRequest((req, res) => {
      cors(req, res, () => {
        var usersRef = ref.child("users");
usersRef.set({
  alanisawesome: {
    date_of_birth: "June 23, 1912",
    full_name: "Alan Turing"
  },
  gracehop: {
    date_of_birth: "December 9, 1906",
    full_name: "Grace Hopper"
  }
});

        if (req.method !== 'POST') {
        return res.status(500).json({
            message: 'Not allowed'
        });
    }
    res.status(200).json({
        message: req.body
    });
      });

});

enter image description here

Upvotes: 1

Views: 2579

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

Your code does write data into the database, under the server node (location). The result in the database is as follows (export from the Firebase console):

  "server" : {
    "saving-data" : {
      "fireblog" : {
        "users" : {
          "alanisawesome" : {
            "date_of_birth" : "June 23, 1912",
            "full_name" : "Alan Turing"
          },
          "gracehop" : {
            "date_of_birth" : "December 9, 1906",
            "full_name" : "Grace Hopper"
          }
        }
      }
    }
  }

So, basically, answer to Question #1 is: "It is saved".

Question #2: The value db.ref("server/saving-data/fireblog") is an instance of a Reference which "represents a specific location in your Database and can be used for reading or writing data to that Database location", see https://firebase.google.com/docs/reference/js/firebase.database.Reference

var usersRef = ref.child("users"); is also a Reference, that you obtain via the child() method, see https://firebase.google.com/docs/reference/js/firebase.database.Reference#child

So, by combining the initial Reference and the child() method, when you do usersRef.set({}) you write to the following path: server/saving-data/fireblog/users. Which is what is reflected above in the export of the database.

Note that with your current code, you will always write the same data at the location, i.e. the following object:

{
  alanisawesome: {
    date_of_birth: "June 23, 1912",
    full_name: "Alan Turing"
  },
  gracehop: {
    date_of_birth: "December 9, 1906",
    full_name: "Grace Hopper"
  }
}

Again, this is reflected above in the export of the database.

With such a Cloud Function, that you call through HTTPS, you would classically get the data you want to write to the database in the body of the HTTP request.


Last point: I would re-organise your function as follows:

const db = admin.database();
const ref = db1.ref("server/saving-data/fireblog");

exports.uploadFile = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        const usersRef = ref.child("users");

        if (req.method !== 'POST') {
            return res.status(500).json({
                message: 'Not allowed'
            })
        } else {
            return usersRef.set({
                alanisawesome: {
                    date_of_birth: "June 23, 1912",
                    full_name: "Alan Turing"
                },
                gracehop: {
                    date_of_birth: "December 9, 1906",
                    full_name: "Grace Hopper"
                }
            }).then(() => {
                res.status(200).json({
                    message: req.body
                });
            }).catch(error => {
                return res.status(500).send(error);
            })
        }

    })

});

Finally, I would suggest you look at thee following video from teh Firebase team: https://www.youtube.com/watch?v=7IkUgCLr5oA

Upvotes: 2

Related Questions