How to use Firebase Database in Google Actions? - dialogflow-es

I'm new to programming Actions for Google Home/Assistant.
I have been using the Inline-Editor under Fulfilment lately and it works fine. Now I want to start using the Firebase DB.
As it says const functions = require('firebase-functions'); in the first lines of the Inline Editor I am assuming, that the Database is ready to use?
If so, how do I access it?

Although Dialogflow uses Firebase Functions to let you do inline code-editing, it doesn't sound like it is a full-fledged Firebase environment. There may be APIs on the back-end that are not setup.
The Dialogflow In-line Fulfillment is meant for simple logic testing and simple operations.
Fortunately - it isn't difficult to take that code and expand it into code that you write... and still host on Firebase Functions! See https://firebase.google.com/docs/functions/get-started for the tools you'll need to install to get started.
For a more extensive tutorial about writing Firebase Functions that work with Dialogflow and getting started with Firebase Functions, you can take a look at the codelab from Google at https://codelabs.developers.google.com/codelabs/assistant-dialogflow-nodejs/index.html

You can use the Google Realtime Database package firebase-admin
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
const db = admin.database();
const ref = db.ref("/");
And to set a value in the database
ref.set({yourKey: 'value'});

Related

How to create a Flutter Stream using MongoDB (watch collection?) with Firebase Cloud Function

I've been trying out MongoDB as database for my Flutter project lately, since I want to migrate from pure Firebase database (some limitations in Firebase are an issue for my project, like the "in-array" limit of 10 for queries).
I already made some CRUD operations methods in some Firebase Cloud Functions, using MongoDB. I'm now able to save data and display it as a Future in a Flutter App (a simple ListView of Users in a FutureBuilder).
My question is : how would it be possible to create a StreamBuilder thanks to MongoDB and Firebase Cloud Functions ? I saw some stuff about watch collection and Stream change but nothing clear enough for me (usually I read a lot of examples or tutorial to understand).
Maybe some of you would have some clues or maybe tutorial that I can read/watch to learn a little bit more about that subject ?
For now, I have this as an example (NodeJS Cloud Function stored in Firebase), which obviously produces a Future in my Future app (not realtime) :
exports.getUsers = functions.https.onCall(async (data, context) => {
const uri = "mongodb+srv://....";
const client = new MongoClient(uri);
await client.connect();
var results = await client.db("myDB").collection("user").find({}).toArray();
await client.close();
return results;
});
What would you advice me to obtain a Stream instead of a Future, using maybe watch collection and Stream change from MongoDB, providing example if possible !
Thank you very much !
Cloud Functions are meant for short-lived operations, not for long-term listeners. It is not possible to create long-lived connections from Cloud Functions, neither to other services (such as you're trying to do to MongoDB here) nor from Cloud Functions back to the calling client.
Also see:
If I implement onSnapshot real-time listener to Firestore in Cloud Function will it cost more?
Can a Firestore query listener "listen" to a cloud function?
the documentation on EventArc, which is the platform that allows you build custom triggers. It'll be (a lot* more. involved though.

Initialising Algolia in Firebase Cloud functions

I am using the Algolia extension for Firebase. In Algolia I have an index with many docuemnts. Each user of my app should access only the documents they created. In order to implement this filter I need to generate a specific, filtered API key in Algolia for each user. I am trying to do this with a cloud function in Fireabse.
I get an error when I try to initialize Algolia in my local cloud functions index.js file and then deploy the functions.
Combining the docs of Cloud Functions and Algolia, I am doing this:
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
// For the default version
const algoliasearch = require('algoliasearch');
// For the default version
// import algoliasearch from 'algoliasearch';
// For the search only version
// import algoliasearch from 'algoliasearch/lite';
const client = algoliasearch('appId', 'AdminApiKey');
const index = client.initIndex('profiles');
I haven't written any Algolia function yet, so I know that the error comes from this initialisation. (My other non-Aloglia cloud functions are running fine). And the Algolia search function installed automatically as a Firebase extension works fine too.
This is the error I get in the terminal when trying to deploying the cloud functions:
Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.
Functions deploy had errors with the following functions:
writeToFirestore(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions
Thank you for any help!
So in the end the problem was that I had not installed the algoliasearch package in the Firebase Cloud Functions directory but in the parent (root) directory of the app.

when i use firebase.database().goOnline(); I get an error

this is my code
admin.initializeApp({...});
var db = admin.database();
let ref = db.ref(...);
await ref.once("value",function () {...},);
firebase.database().goOffline();
firebase.database().goOnline();
ref.on("value",function () {...},);
);
when i use firebase.database().goOnline(); I get an error
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
at app
You're mixing two ways of addressing Firebase.
You can access Firebase through:
Its client-side JavaScript SDK, in which case the entry point is usually called firebase.
Its server-side Node.js SDK, in which case the entry point is usually called admin.
Now you initialize admin, but then try to access firebase.database(). And since you did call admin.initializeApp that's where the error comes from.
My guess is that you're looking for admin.database().goOnline() or db.goOnline().
Also note that there is no reason to toggle goOffline()/goOnline() in the way you do now, and you're typically better off letting Firebase manage that on its own.

can i run a node function on a react app directly

I am making a react app where I need to fetch some data using an API.
I want to deploy this app with Netlify so I cannot use a backend. So, I wrote a Firebase Cloud Function to handle the fetching. However, Google wouldn't allow third-party API requests on the free plan.
So either I have to learn using AWS or I will write a backend and deploy using another service.
Honestly, I don't want to do either. So, my question is, can I call this node function directly inside my react app if so how and is it advisable, if not are there any other alternatives?
The function is something like this:
const functions = require("firebase-functions");
const League = require("leagueapiwrapper");
require("dotenv").config();
exports.getFavorites = functions.https.onCall(async (data, context) => {
try {
const LeagueAPI = new League(process.env.API_KEY, Region.TR);
...
The only thing that actually requires node is the leagueapiwrapper package. (Obviously I will get rid of firebase related stuff).

Is it possible to have a Firebase Function that is triggered by changes to a Firestore that lives in a seperate Firebase project to the Function?

Let's say I have a Firebase project named "A". Within this project, I have a Cloud Firestore triggered Firebase function that needs to run when a document within Firestore changes. By default, the Firebase Function will listen to changes within Firestore on project A.
However, let's say I have a particular use case where there is a second Firebase project named "B". I need the Firebase Function within Project A to be triggered on Firestore changes that happen to Firestore within project B.
Is this possible? Firebase docs do show initializing multiple projects, which would allow me to connect to multiple databases as such:
const admin = require("firebase-admin");
const serviceAccount = require("path/to/serviceAccountKey.json");
const secondaryAppConfig = {
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
};
// Initialize another app with a different config
const secondary = firebase.initializeApp(secondaryAppConfig, "secondary");
// Retrieve the database.
const secondaryDatabase = secondary.database();
But this doesn't allow me to trigger a Firestore Triggered Firebase Function on my secondary project. Firebase functions call the firebase-functions methods directly, whereas calling a database calls the initialized project.
const functions = require('firebase-functions');
exports.myFunction = functions.firestore
.document('...')
.onWrite((change, context) => { /* ... */ });
Is what I would like to do possible? Or does anyone have a workaround (other than creating this Firebase Function within project B)?
It's not possible. Cloud Functions triggers can only fire in response to changes in the resources of the project where they are deployed. This is true for all types of triggers, including Firestore.
If you want code to run in response to changes in another project, the function will have to be deploy to that project.
Currently it is only possible for writes to Cloud Firestore to trigger Cloud Functions that are part of the same project. It is not possible to trigger Cloud Functions that are defined in another project.
The typical solution is for example to call a HTTP Function in the secondary project, for which you can then configure the complete URL.
I'm not sure it can be done all in one codebase - that's from a lack of experience though. I'd say, given your setup, your calling function can trigger your callee function via HTTP call (documentation)
This might require a paid Firebase plan, but I'm not certain of it (source)

Resources