3

I have a third party API that I need to call every 5 seconds. I get JSON as response, and I'd like to write the JSON content to a Firebase node using Node.js. Based on Firebase examples I could import data with this code:

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"
  }
});

Curl examples worked too. But what I really wanted to do is to import a third party API response directly to my Firebase database using the API endpoint. How can i do it with Node.js?

2 Answers 2

5

First, you need to make a request to the api endpoint and receive the data. Then, you can send that json data to firebase

var request = require('request');

var usersRef = ref.child("users");

request('<your_endpoint>', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var asJson = JSON.parse(body)
    usersRef.set(asJson)
   }
})
Sign up to request clarification or add additional context in comments.

Comments

0

I ran into a lot of little "gotchas" implementing the sample node.js code from the Firebase docs. Below is a fully working code set correcting all the issues which will run as a Google Cloud Platform function (node.js v8 - async/await will not work in v6):

const admin = require('firebase-admin');
// You need this library in order to use firebase in functions
const functions = require('firebase-functions');

/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
exports.uploadFile = async (req, res) => {

  // Check if firebase is already initialized, per: https://maxrohde.com/2016/09/21/test-if-firebase-is-initialized-on-node-js-lambda/
  if (admin.apps.length === 0) {
    admin.initializeApp(functions.config().firebase);
  }

  var db = admin.firestore();
  var message = '';

  createUsers(db);
  message = await getUsers(db);

  res.status(200).send('Database content:\n' + message);
};

// Write data in a function so you can wait for all the Promises to complete and return per: https://github.com/firebase/functions-samples/issues/78
function createUsers(db) {
  var docRef = db.collection('users').doc('alovelace');

  var setAda = docRef.set({
    first: 'Ada',
    last: 'Lovelace',
    born: 1815
  })
  .catch((err) => {
    console.log('Error writing document', err);
  });

  var aTuringRef = db.collection('users').doc('aturing');

  var setAlan = aTuringRef.set({
    'first': 'Alan',
    'middle': 'Mathison',
    'last': 'Turing',
    'born': 1912
  })
  .catch((err) => {
    console.log('Error writing document', err);
  });

  return Promise.all([setAda, setAlan]);
}

async function getUsers(db) {
  var message = '';
  await db.collection('users').get()
    .then((snapshot) => {
      snapshot.forEach((doc) => {
        // You need to stringify doc.data() if you want to render it outside of a console.log()
        message += '\n' + doc.id + '=>' + JSON.stringify(doc.data());
      });
    })
    .catch((err) => {
      console.log('Error getting documents', err);
    });

    return message;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.