3

I have a firebase database that I wish to create a cloud function that triggers when adding a child node to the parent node , which should call a url with the parameters of the child node added in the parent node.

The URL which would be called is a NodeJS Express app hosted in Google App Engine.

How do I do that, if it is even possible?

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Famic Tech
  • 280
  • 5
  • 20

1 Answers1

2

You can use the node.js request library to do so.

Since, inside your Cloud Function, you must return a Promise when performing asynchronous tasks, you will need to use an interface wrapper for request, like request-promise.

You could do something along these lines:

.....
var rp = require('request-promise');
.....

exports.yourCloudFucntion = functions.database.ref('/parent/{childId}')
    .onCreate((snapshot, context) => {
      // Grab the current value of what was written to the Realtime Database.
      const createdData = snapshot.val();

      var options = {
          url: 'https://.......',
          method: 'POST',
          body: ....
          json: true // Automatically stringifies the body to JSON
      };

      return rp(options);

    });

If you want to pass parameters to the HTTP(S) service/endpoint you are calling, you can do it through the body of the request, like:

      .....
      const createdData = snapshot.val();

      var options = {
          url: 'https://.......',
          method: 'POST',
          body: {
              some: createdData.someFieldName
          },
          json: true // Automatically stringifies the body to JSON
      };
      .....

or through some query string key-value pairs, like:

      .....
      const createdData = snapshot.val();
      const queryStringObject = { 
         some: createdData.someFieldName,
         another: createdData.anotherFieldName
      };

      var options = {
          url: 'https://.......',
          method: 'POST',
          qs: queryStringObject
      };
      .....
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • How would I pass parameters as well? Like the child node name and associated value ex the child information would be like: `2017-11-11 12:23:11` and value `123847271` – Famic Tech Sep 26 '18 at 22:07
  • It depends on the service you are calling. How should you pass these parameters? Through the body? As query strings? – Renaud Tarnec Sep 26 '18 at 22:09