Starting on a new React JS site with Firebase

27th Sep 19
narrow street

I will be going through the steps I in building the backend of my site using Firebase.

I am creating a few functions in Firebase to fetch, post and filter data.  So after setting up a project in Firebase, I install firebase globally with npm. 


$ npm install -g firebase-tools

Then you need to login with your firebase credentials by running the command:

firebase login

Within my project, I then initialise:

firebase init

When you initialise you will be asked what do you want included.  I selected firebase functions, as I will be using functions to create the backend endpoints.

Then I go to my firebase project, to the database to set up a collection.  I start with creating a collection with the bare minimum amount of data, such has the tree name, description and family or sub-section.  

I then go to the index where I create my first function. Before that I need to bring in firebase-admin (already installed) and initialise the admin app to allow access to the database.  

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();

 

Then I added the below function

exports.getBonsais = functions.https.onRequest((req, res) => {
 admin.firestore().collection('bonsais').get()
    .then(data => {
        let bonsais = [];
        data.forEach(doc => {
            bonsais.push(doc.data())
        });
        return res.json(bonsais);
    })
    .catch(err => console.error(err));
})

returning the data of the 'bonsais'.  A collection is a group of data, like a table in mySql.  Before testing my function I need to run 

firebase deploy

Then I go to Postman, with the endpoint provided in the console and run a GET request.  It successfully returns the data in json format.

 

postman

I then created a route for posting a 'bonsai', allowing to send a post request: 

exports.createBonsai = functions.https.onRequest((req, res) => {
    const newBonsai = {
        body: req.body.body,
        family: req.body.family,
        name: req.body.name
    };
    admin.firestore()
        .collection('bonsais')
        .add(newBonsai)
        .then(doc => {
            res.json({message: `document ${doc.id} created successfully`})
        })
        .catch(err => {
            console.error(err); 
            res.status(500).json({error: 'something when wrong'})
        })
   });

 

For posting data, you will need to set up your firebase admin SDK authentication.  Within your firebase project go to project settings -> service accounts and follow the instructions from there.

I have recently completed my apprenticeship.  I am currently building the API to a React JS site using Firebase.