I use a cloud function as a webhook receiver, so every time I get a webhook I want to update firestore with some data for example. I don’t get how to use firestore in my clound function.
I tried this:
JavaScript
x
7
1
const admin = require("firebase-admin");
2
3
4
admin.initializeApp();
5
6
res.send(admin.database().ref("/tmp_list/1uMW9ED3YGMfERHZiKJc").get());
7
All do not seem to be able to initilise this. I also tried:
JavaScript
1
2
1
admin.initializeApp(functions.config().firebase);
2
Advertisement
Answer
As explained in the documentation, the following should do the trick:
JavaScript
1
5
1
const functions = require('firebase-functions');
2
3
const admin = require('firebase-admin');
4
admin.initializeApp();
5
Then, to interact with the Realtime Database in an HTTPS Cloud Function you should do along the following lines:
JavaScript
1
12
12
1
exports.date = functions.https.onRequest(async (req, res) => {
2
const db = admin.database();
3
4
const dataSnapshot = await db.ref("tmp_list/1uMW9ED3YGMfERHZiKJc").get();
5
6
const data = dataSnapshot.val();
7
8
// ...
9
10
res.send(data);
11
});
12
Since you tagged your question as google-cloud-firestore
, note that in order to interact with Firestore in an HTTPS Cloud Function you should do as follows:
JavaScript
1
12
12
1
exports.date = functions.https.onRequest(async (req, res) => {
2
const db = admin.firestore();
3
4
const docSnapshot = await db.doc("tmp_list/1uMW9ED3YGMfERHZiKJc").get();
5
6
const data = docSnapshot.data();
7
8
// ...
9
10
res.send( )
11
});
12
I recommend you watch the following official video.