Google Cloud function to fetch data from third party server
UPDATE on 8 May 2020
request-promise
being now deprecated, I recommend to use axios
.
You can use the node.js request-promise library to do so.
You could do something along these lines, for example:
.....
var rp = require('request-promise');
.....
exports.yourCloudFunction = 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
};
.....
IMPORTANT:
Note that if you plan to call a non Google-owned service (like the "third party server" you mentioned), you need to be on the "Flame" or "Blaze" pricing plan.
As a matter of fact, the free "Spark" plan "allows outbound network requests only to Google-owned services". See https://firebase.google.com/pricing/ (hover your mouse on the question mark situated after the "Cloud Functions" title)
UPDATE FOLLOWING YOUR COMMENT:
If you want to trigger a call to the third party server and then populate the Firebase Realtime Database with data received from this server you could do as follows. I took an example of call to an API from the request-promise documentation: https://github.com/request/request-promise#get-something-from-a-json-rest-api.
You would then call this Cloud Function regularly with an online CRON job like https://www.easycron.com/.
exports.saveCallToAPI = functions.https.onRequest((req, res) => {
var options = {
uri: 'https://api.github.com/user/repos',
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(repos => {
console.log('User has %d repos', repos.length);
const dbRef = admin.database().ref('userName'); //For example we write to a userName node
var newItemRef = dbRef.push();
return newItemRef.set({
nbrOfRepos: repos.length
});
})
.then(ref => {
response.send('Success');
})
.catch(error => {
response.status(500).send(error);
});
});
Here's how to do it using node-fetch.
Your Cloud Function:
const fetch = require('node-fetch');
exports.functionName= (req, res) => {
const fetchFromURL = async () => await (await fetch('https://yourURL.com')).json();
fetchFromURL().then((data) => {
// do something with data (received from URL).
});
};
You will need to add the "node-fetch" dependency to your function's package.json as well.
Your package.json:
{
"name": "sample-http",
"version": "0.0.1",
"dependencies": {
"node-fetch": "^2.6.1"
}
}