m00saca
m00saca

Reputation: 363

Trouble connecting Firebase database to Express.js server

Good afternoon everyone I am in a little trouble trying to connect my express server to my firebase database. I am making an app that makes api calls to my express server that in turn with information sent from my client makes an api call to this halo api. From there the information given back to me from halo's server is given back to my express server which gives an object back to my client to populate the DOM.

Everything described above I have gotten to work, yay, but now I want o incorporate a firebase database and things are not so perfect. What I want to be able to do is add more functionality with my app. So when that api call is made from my express server (app.js) to halo's server I want to send data to my firebase database instead of back to the client. To me it seems easy in practice to instead take the data object I receive from halo, I'm just calling it halo for now because it's easier, and send it to my firebase database. From there I would use the database to populate the DOM.

As I mentioned earlier, in practice this is proving much more difficult. I need to use firebase in the first place because I need to add CRUD functionality to this app so just not using it is out of the question. currently when running my server I receive this error in the command line after running nodemon src/app.js:

/Users/MMac/Desktop/haloApp/src/app.js:28
var dbReference =  new Firebase("https://haloapp-5cfe2.firebaseio.com/");
                   ^

TypeError: Firebase is not a function
    at Object.<anonymous> (/Users/MMac/Desktop/haloApp/src/app.js:28:20)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:968:3

Based on this error I'm thinking that I'm not requiring the correct file for firebase but I just don't know which one to include. I installed the node package for firebase and the tutorials I have read just use var Firebase = require("firebase");

This is my app.js file:

"use-strict"

var express = require("express");
//dependencies
var request = require("request");
var Options = require("./router.js")
var app = express();
var bodyParser = require("body-parser");
var Firebase = require("firebase");

Firebase.initializeApp({
  databaseURL: "[databaseURL]",
  serviceAccount: {
  "type": "service_account",
  "project_id": "haloapp-5cfe2",
  "private_key_id": "[some number]",
  "private_key": "[redacted]",
  "client_email": "[email protected]",
  "client_id": "[my client ID]",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/haloappservice%40haloapp-5cfe2.iam.gserviceaccount.com"
}

});

var dbReference =  new Firebase("https://haloapp-5cfe2.firebaseio.com/");

Also here is my package.json file just incase:

{
  "name": "haloapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.15.1",
    "express": "^4.13.4",
    "firebase": "^3.0.5",
    "nodemon": "^1.9.2"
  }
}

I appreciate anyone taking the time to look at this issue and provide their own two cents. Thanks a lot and let me know how I can help you by providing anything else.

Upvotes: 2

Views: 1355

Answers (1)

m00saca
m00saca

Reputation: 363

Using this code I was able to connect to firebase on the backend:

"use-strict"

var express = require("express");
//dependencies
var request = require("request");
var Options = require("./router.js")
var app = express();
var bodyParser = require("body-parser");
var Firebase = require("firebase");

Firebase.initializeApp({
  databaseURL: "[databaseURL]",
  serviceAccount: {
  "type": "service_account",
  "project_id": "haloapp-5cfe2",
  "private_key_id": "[some number]",
  "private_key": "[redacted]",
  "client_email": "[email protected]",
  "client_id": "[my client ID]",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/haloappservice%40haloapp-5cfe2.iam.gserviceaccount.com"
}

});

// links to my firebase database
var db = Firebase.database();
//sets the reference to the root of the database, or the server I'm not quite sure.
var ref = db.ref("/");

And here is an example API call that sends data to the database:

//Event Listener when there is a POST request made from public/request.js
app.post("/statSearch", function(req, res){
    // In this case the req is the POST request and the request body is the data I sent along with it. Refer to request.js
    var search = req.body.search;

    var statsOptions = new Options("https://www.haloapi.com/stats/h5/servicerecords/warzone?players="+search);

        request(statsOptions, function (error, response, body) {
          if (error) throw new Error(error);
          // This is necessary because the body is a string, and JSON.parse turns said string into an object
          var body = JSON.parse(response.body)

          var playerData = {
            gamertag: body.Results[0].Id,
                totalKills: body.Results[0].Result.WarzoneStat.TotalKills,
                totalDeaths: body.Results[0].Result.WarzoneStat.TotalDeaths,
                totalGames: body.Results[0].Result.WarzoneStat.TotalGamesCompleted
          };
        res.send(playerData)
        //console.log(playerData);
    // creates a child named "user" in my database
    var userRef = ref.child("user");
    // populates the child with the playerData object successfully.
    // Every time a new POST request is issued the user's data resets.
    userRef.set(playerData)
        });
});

This code writes data to my database!

Upvotes: 1

Related Questions