How to trigger Cloud Functions from Google cloud firestore - firebase

How to send the DocumentReference.getId() that is generated every time a new document was added to firestore from Android Studio to cloud function that triggers when there is a write/create operation on Firestore.
I tried following
'use strict';
const https = require( 'firebase-functions');
const functions = require('firebase-functions');
const Firestore = require('#google-cloud/firestore');
const firestore = new Firestore();
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.helloUser = functions.firestore
.document('BankInform/Moj2HBrxepX5R7FonvrO')
.onUpdate(event =>{
var newValue = event.data.data();
return event.data.ref.update({
"status": "Success"
});
});
But I have to give the autoid of document.How to pass document id from android studio to cloud functions

You want to use wildcards in your function:
exports.helloUser = functions.firestore
.document('BankInform/{transactionId}')
.onUpdate(event =>{
var transactionId = event.params.transactionId
console.log(transactionId); // Moj2HBrxepX5R7FonvrO
});
As you can see, you should be able to use event.params to get the appropriate document name from the function.

Related

update firebase upon cloud storage thumbnail completion

I have the following index.js that's triggered when a thumbnail is generated in cloud storage. It seems to work fine.
I'd like to replace the console.log line with code that adds a field like {"thumbnail_done":true} to the firebase document docid found in the script. I'm not clear on how to do that.
exports.thumbComplete = (event, context) => {
const fname = event.name;
let suffix = "_200x200.jpeg"
if (fname.endsWith(suffix)) {
let docid = fname.substring(0, fname.length - suffix.length);
console.log(`thumbnail processing complete: ${docid}`);
}
};
Thanks!
Got it working with the following:
// The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
exports.generateThumbnail = functions.storage.object().onFinalize(async (object) => {
const fname = object.name;
let suffix = "_200x200.jpeg"
if (fname.endsWith(suffix)) {
let docid = fname.substring(0, fname.length - suffix.length);
await admin.firestore().doc(`photo/${docid}`).update({ 'uploaded': true });
}
});

Firebase Cloud Function not executing Flutter

I have the following function in my index.ts file:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
const fcm = admin.messaging();
export const sendToDevice = functions.firestore
.document('orders/{orderId}')
.onCreate(async snapshot => {
print("aa")
console.log("osakosak");
const order = snapshot.data();
const querySnapshot = await db
.collection('users')
.doc(order.ustaID)
.collection('tokens')
.get();
const tokens = querySnapshot.docs.map(snap => snap.id);
const payload: admin.messaging.MessagingPayload = {
notification: {
title: 'New Order!',
body: `you sold a ${order.day} for ${order.time}`,
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
};
return fcm.sendToDevice(tokens, payload);
});
However, when the new document gets added into the order collection, this doesn't get triggered. Even the print and console.log don't work. I tried putting print and console log before export, and it still didn't fire.
Based on your comments ("It depends on cloud_firestore in pubspec.yaml"), it seems that you didn't deploy your Cloud Function correctly.
As a matter of fact, Cloud Functions are totally independent from your Flutter app (your front-end). It is a back-end service. You should deploy it with the Firebase CLI, see the doc. Note that the code shall be in the Firebase Project, not in your Flutter project.

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

firebase firestore presence system

I am trying to implement a presence system, I have followed the documentation for it. it works as it updates both my firestore and realtime databases. However, when i close the app, the realtime database is updated, while the firestore is not. below is the sample code I have in my cloud function, which I assume performs the action.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const firestore = admin.firestore();
exports.onUserStatusChanged = functions.database.ref('/status/{uid}').onUpdate(
async (change, context) => {
const eventStatus = change.after.val();
const userStatusFirestoreRef = firestore.doc(`users/${context.params.uid}`);
const statusSnapshot = await change.after.ref.once('value');
const status = statusSnapshot.val();
console.log(status, eventStatus);
if (status.last_changed > eventStatus.last_changed) {
return null;
}
return userStatusFirestoreRef.set({
online: false,
last_changed: firestore.FieldValue.serverTimestamp(),
}, { merge: true });
});

Firestore Cloud Function Times Out When called

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

Resources