Answer the question
In order to leave comments, you need to log in
How to get data from Firebase Database through Firebase Admin in Firebase Functions?
Task:
Using the Firebase Functions http trigger, get all records in the Firebase Database once, that is, through the once method.
The code:
const functions = require('firebase-functions');
const admin = require("firebase-admin");
const serviceAccount = require("path/to/serviceAccount.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://<database>.firebaseio.com/"
});
var db = admin.database();
var ref = db.ref("/data");
exports.resend = functions.https.onRequest((request, response) => {
return ref.once("value").then((data) => {
console.log('done');
response.status(200).send("OK");
}).catch((error) => {
console.log('error', error);
response.status(500).send("Error");
});
});
Answer the question
In order to leave comments, you need to log in
As a result, I decided to create a base listener separately from the method that saves all the data to an array, and analyze the data in the array using an HTTP trigger. Thanks to all! Code below.
ref.on("value", function(snapshots) {
data = [];
snapshots.forEach(function(record) {
var val = record.val();
var value = val.value;
data.push({ value: value });
});
});
exports.resend = functions.https.onRequest((request, response) => {
var query = request.query;
var value = query.value;
for (var i = 0; i < data.length; i++)
{
var item = data[i];
if (item['value'] == value)
response.status(200).send("OK");
}
response.status(500).send("Value not found");
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question