Firestore Cloud Function Times Out When called - firebase

I have a custom endpoint setup for my FireStore database.
For now, all I want is to print all values to console, but when I call it from a client, the request times out and the console only says:
#firebase/database: FIREBASE WARNING: The Firebase database
'project-name' has been disabled by a database owner.
(https://project-name-de56eb8.firebaseio.com)
Here's my code. Can anyone tell me what is (what thins are) wrong with it?
const util = require('util');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const language = require('#google-cloud/language');
const client = new language.LanguageServiceClient();
const express = require('express');
const app = express();
app.post('/calculateAverage', async (request, response) => {
const bodyUserId = request.body.id
let query = admin.database().ref(`/user_info/`);
try {
const snapshot = await query.once('value');
snapshot.forEach((childSnapshot) => {
console.log("key: " + childSnapshot.key + " value: " + childSnapshot.val())
});
response.send({"snapshot await": "ok"});
} catch(error) {
console.log('Error getting messages', error.message);
response.send({"snapshot await error": error.message});
}
});
exports.api = functions.https.onRequest(app);

The problem is that you no use firebase realtime data.
in the options of firebase you have database and next *Cloud Firestore and
*Realtime Database, select Realtime Database and after, active this option and with this the solution

Related

Connecting Dialogflow to Firebase question

I have been reading around but cannot find the answer
I tried my firebase and it's not storing any data.
Here's the related inline editor
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
function angerEmotionCapture(agent) {
let angryTo = agent.parameters.angryDirectedTo;
agent.add(`love your ${angryTo},dude`);
return db.collection('directedTo').add({directedTo: angryTo});
}
Here's my firebase database
Any help will be greatly appreciated, thanks!
Please have a look into the following sample code showing how to connect Firebase's Firestore database to Dialogflow fulfillment hosting on Firebase functions:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {WebhookClient} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:*'; // enables lib debugging statements
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
function writeToDb (agent) {
// Get parameter from Dialogflow with the string to add to the database
const databaseEntry = agent.parameters.databaseEntry;
// Get the database collection 'dialogflow' and document 'agent' and store
// the document {entry: "<value of database entry>"} in the 'agent' document
const dialogflowAgentRef = db.collection('dialogflow').doc('agent');
return db.runTransaction(t => {
t.set(dialogflowAgentRef, {entry: databaseEntry});
return Promise.resolve('Write complete');
}).then(doc => {
agent.add(`Wrote "${databaseEntry}" to the Firestore database.`);
}).catch(err => {
console.log(`Error writing to Firestore: ${err}`);
agent.add(`Failed to write "${databaseEntry}" to the Firestore database.`);
});
}
// Map from Dialogflow intent names to functions to be run when the intent is matched
let intentMap = new Map();
intentMap.set('WriteToFirestore', writeToDb);
agent.handleRequest(intentMap);
});
Have a look into the Dialogflow's Firestore GitHub example

Arduino SIM800L Firestore database security rules

I want to post data in a Firestore database using Arduino with the SIM800L module.
I have already done a test in which I use Firebase Database Realtime which works well but without configuring the security.
Now I use a Firestore database by configuring security.
I read the official documentation but I do not know how Arduino should make the request to enter the authentication information.
Update my question.
here is the code that I use with the Realtime database without security configuration.
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp();
exports.helloWorld = functions.https.onRequest((req, res) => {
res.send('identifiant: ' + req.body.identifiant);
});
exports.insertMesure = functions.https.onRequest((req, res) => {
const identifiant = req.body.identifiant;
const temperatureAir = req.body.temperatureAir;
const humiditeSol = req.body.humiditeSol;
const humiditeAir = req.body.humiditeAir;
const niveauEau = req.body.niveauEau;
const phSol = req.body.phSol;
const dateMesure = Date.now();
const mesure = {
temperatureAir: temperatureAir,
humiditeSol: humiditeSol,
humiditeAir: humiditeAir,
niveauEau: niveauEau,
phSol: phSol,
dateMesure: dateMesure
};
const dbRef = admin.database().ref('/users/' + identifiant + '/mesures');
dbRef.push(mesure)
.then(() => {
return res.status(200).send('oK');
})
.catch(err => {
res.status(500).send('Error: ' + err);
});
});
The structure of my database:
- users
- {user_id}
- mesures
Replaced
user_id
by the identifier attribute
identifiant
of the request sent by Arduino

Unable to fetch data from firestore database

I am working on a dialogflow agent and using fulfillment to fetch data from the firestore.
I have a firestore collection called Users which has name and location fields. But am getting the error which causes the fetching of data to fail.
Warning, estimating Firebase Config based on GCLOUD_PROJECT.
Initializing firebase-admin may fail
The fulfillment code for the agent is as follows
'use strict';
const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const { Card, Suggestion } = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
var name='';
var location='';
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
function getUserDetails(agent)
{
name= agent.parameters.name;
location=agent.parameters.location;
console.log("buyer name is " + name);
db.collection("Users").doc("101").set({
name: name,
location:location});
agent.add(`User has been inserted`);
}
intentMap.set('Buy Car', getUserDetails);
agent.handleRequest(intentMap);
})
This form of initialization for the Firebase Admin SDK is deprecated:
admin.initializeApp(functions.config().firebase);
You should initialize like this instead:
admin.initializeApp();

Unable to Access Firestore Document Within a Firestore Cloud Function

Issue: Type Error
I setup a Firestore Cloud Function to call from my Android app which is being called as expected, however I am unable to access a Firestore document from within the method and receiving a TypeError in the logs.
Attempted Solutions
functions.firestore().document('qa/content/feeds/main/content/'+contentTitle)
functions.firestore().ref('qa/content/feeds/main/content/'+contentTitle)
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();
const MAIN_FEED_TYPE = "MAIN";
const SAVED_FEED_TYPE = "SAVED";
const ARCHIVED_FEED_TYPE = "ARCHIVED";
const SAVE_USER_ACTION = "SAVE";
const ARCHIVE_USER_ACTION = "ARCHIVE";
const SAVED_PATH = "saved"
const ARCHIVED_PATH = "archived"
exports.updateQualityScore = functions.https.onCall((data, context) => {
const environment = data.environment
const feedType = data.feedType
const action = data.action
const contentTitle = data.contentTitle
const uid = context.auth.uid;
var feedTypePath
if (feedType === SAVED_FEED_TYPE) {
feedTypePath = SAVED_PATH
} else if (feedType === ARCHIVED_FEED_TYPE) {
feedTypePath = ARCHIVED_PATH
}
admin.firestore().ref('qa/content/feeds/main/content/'+contentTitle)
.get().then(function(doc) {
console.log('Trigger fired on content: '
+ contentTitle + " | user: " + uid
+ " | action: " + action + ' | feedType: ' + feedType);
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
console.log("No such document!");
}
return {
status: 'Get content success.'
}
}).catch(function(error) {
console.log("Error getting document:", error);
return {
status: 'Get content error.'
}
});
});
Firestore doesn't have a ref() method. Realtime Database does. You're probably confusing the two.
With Firestore, you deal with collections and documents, and there are different methods to get a hold of collection and document references. Maybe you meant to use the doc() method instead, like this?
admin.firestore().doc('qa/content/feeds/main/content/'+contentTitle)
Sorry wrong answer.
You need to pass credential when initializing app.
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
or
admin.initializeApp({
credential: admin.credential.cert({
projectId: '<PROJECT_ID>',
clientEmail: 'foo#<PROJECT_ID>.iam.gserviceaccount.com',
privateKey: '-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n'
}),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
initialize the sdk
Quick Start

Accessing Firebase Firestore on AWS Lambda

I have following problem
I am writing a lambda function which is gets a post value offer an API, than checks in firebase firestore if the value is there and than replies to the client. Simple.
This is my code:
const serverless = require("serverless-http")
const express = require("express")
const app = express()
const bodyParser = require("body-parser")
const cors = require("cors")
const admin = require("firebase-admin")
var login = require("./test.json")
admin.initializeApp({ credential: admin.credential.cert(login) })
const db = admin.firestore()
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.post("/", function(req, res) {
let result = req.body.code.toUpperCase()
db.collection("voucher")
.get()
.then(x => {
console.log("TEST")
console.log(x)
})
.catch(err => res.status(400).send({ err }))
})
module.exports.voucher = serverless(app)
The API works just fine, problem is connecting to the firestore, the error object I get always says:
{code: "MODULE_NOT_FOUND"}
I did it how it is shown in the tutorial here:
https://firebase.google.com/docs/firestore/quickstart
But it does not seem to work at all.
I downloaded the correct credentials, actually I gave myself admin access to everything. But still it does not work.
You guys have any suggestions?

Resources