Issue with Firebase Cloud function.. not able to read parameters - node.js

I am not uunderstanding why this is not working, as it is basic.
Here is my code:
// Init cloud functions
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// Used to access entire JSON Nodes as Admin...
admin.initializeApp();
exports.verifyIAP = functions.database.ref('/Users/{userid}/IAP/{groupid}/{rdate}')
.onCreate((snapshot, context) => {
const groupId = context.params.groupid;
console.log('GroupID: ', groupId);
const receiptDate = context.params.rdate;
console.log('receipt Date: ', receiptDate);
const userId = context.params.userid;
console.log('UserID: ', userId);
const receipt = snapshot.val().ReceiptData;
console.log('receipt Data: ', receipt);
});
When the function triggers, the log shows all the variables as undefined!?
What am I missing!?

Your function is working fine. I just tested it and the problem can be pointed on how you insert the data. For testing purposes, Here's a sample code I used to insert data and trigger the function:
// Import Admin SDK
var admin = require("firebase-admin");
var serviceAccount = require("./*******.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://********.firebaseio.com/"
});
var db = admin.database();
var ref = db.ref("Users");
ref.set({
"userId" : {
"IAP" : {
"groupId" : {
"rdate" : {
"ReceiptData" : "testVAl"
}
}
}
}
}).then(result => {
console.log('done')
process.exit(0)
});

Related

"Parsing error: Unexpected token db" in index.js file

I have 2 trigger functions in an index.js file.
const functions = require("firebase-functions");
//const addTrxns = require("./trxnAdd.js");
const admin = require("firebase-admin");
const { user } = require("firebase-functions/lib/providers/auth");
const { event } = require("firebase-functions/lib/providers/analytics");
//exports.addTrxns.addTrxns;
admin.initializeApp();
const db = admin.firestore();
exports.userProfileChanged = functions.firestore.document('/agents/{userId}').onWrite( async (change, context) => {
const userId = context.params.userId;
console.log('A change has been made to user profile');
const getUserDeviceToken = await db.collection('device').doc(userId).get();
.
.
.
return Promise.all(console.log('End of function'));
});
/* ======================================================================== */
exports.onTrxnCreate = functions.document('/trxns/{trxnId}').onCreate((snap, context) => {
const userId = context.params.userId;
console.log('A new transaction has been added');
const getUserDeviceToken = await **db.collection('device').doc(userId).get();**
return Promise.all(console.log('End of function'));
});
I get this error, "Parsing error: Unexpected token db" in the second function. I think it has something to do with the "await" but I don't know enough about this to fix it. How can I fix this error?
Thanks.
I figured this out. I was missing "async" in the second function.

Express JS: Send Databse as Variable / Parameter while requiring a module

Say I have the following code
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const serviceAccount = require("./permissions.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://blah-blah-blah.firebaseio.com"
});
const db = admin.firestore();
app.use("/auth", require("./auth"));
Now the problem is that I have to use the cloud firestore databse functionality, which is curently stored in the variable db, in my auth.js file as well, without using admin.initializeApp a second time. Is there any way to acomplish that, like importing/exporting the db variable etc.
This is where I am using it in auth.js:
const express = require("express");
const auth = express.Router();
db.collection("data")
.doc("sample")
.get()
.then(
document => {
if (document.exists) {
return done(null, {
id: user.id,
name: user.name,
email: user.email
});
} else {
//create document
}
},
err => {
//handle error
}
);
Of course, right now db will be undefined, which is the problem I need to tackle
Since version 1.0.0 of the Firebase SDK for Cloud Functions you have to initialize with admin.initializeApp();, see the doc here.
Then, to interact with Firestore, you just need to use the Admin SDK, for example as follows:
admin.firestore().collection('....').get();
So, if I understand correctly your question, the following changes should do the trick:
index.js
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
//const db = admin.firestore(); not sure you need that here, it depends if you interact (or not) with Firestore in index.js
app.use("/auth", require("./auth"));
auth.js
const admin = require("firebase-admin");
const db = admin.firestore();
//....
db.collection("data")
.doc("sample")
.get()
.then(
document => {
if (document.exists) {
return done(null, {
id: user.id,
name: user.name,
email: user.email
});
} else {
//create document
}
},
err => {
//handle error
}
);
//....

Error upon Cloud Function for Firebase deployment

I've been trying to deploy a Cloud Function to my Firebase project.
It's my first time doing so, also my first time programming with JavaScript.
Here's my code in Node.JS:
'use strict'
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
const firebaseTriggers = functions.region('europe-west1').firestore;
const db = admin.firestore();
exports.postNotification = firebaseTriggers
.document('/post notifications/{notificatioId}').onWrite((snap, context) => {
const notifcationRecieverId = snap.data().mReciever;
const payload = {
data: {
notification_type: 'POST',
title: snap.data().mTitle,
body: snap.data().mDescription,
sender_id: snap.data().mSender,
reciever_id: snap.data().mReciever,
notification_id: context.params.notificatioId
}
};
return db.collection('dog owners')
.document(notifcationRecieverId)
.get()
.then(recieverDoc => {
console.log('Retrieving FCM tokens');
const tokens = recieverDoc.data().mTokens;
console.log('Sending notification payload');
return admin.message().sendToDevice(tokens, payload);
});
});
Upong deployment, I'm getting the following error:
Can someone help me understand why?
Firstly you have got space in your colleciton name. This is bad convetion.
post notifications => postNotifications

Node.js cloud function "firestore set() inside get() if not exists" is not working correctly?

Here is I'm trying to achieve
if user is exist in firestore
show the data
else
add it to firestore
And following is my code
// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
var db = admin.firestore();
const settings = {timestampsInSnapshots: true};
db.settings(settings);
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
function save(agent) {
const usersRef = db.collection('users').doc('someid');
usersRef.get().then(function(doc) {
if(doc.exists) {
let existingUser = doc.data();
console.log("Document is already exists " + existingUser.userName);
agent.add('Hello ');
} else {
console.log("Document creation is started");
usersRef.set({
userName : 'somename'
});
agent.add('Welcome ');
}
}).catch(function(error) {
console.error("Error writing document: ", error);
agent.add('Failed to login!');
});
}
let intentMap = new Map();
intentMap.set('dialogflow-intent-name',save);
agent.handleRequest(intentMap);
});
But the execution of above code it starts the cloud function and terminated first and my chatbot doesn't get any response but after execution log is like
Function execution started
Function execution took 404 ms, finished
with status code: 200
"Document is already exists someusername"
DocumentReference.set returns a promise, and you are not waiting for it to finish. So it should work if you change your code from:
usersRef.set({
userName : 'somename'
});
... rest of the code
to
usersRef.set({
userName : 'somename'
}).then(result => {
... rest of the code
})

Cloud Functions that add a new collection to the already existing document in firestore

I want to add new collection to a doc that already exists in firestore.Is it possible? The following is the code for doing that, I used cloud fucntions for doing that.Whenever a document is created in firestore then the following cloud function has to trigger
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.myWallet = functions.firestore
.document('Samyata/{authid}')
.onCreate(event =>{
const ID = event.params.authid
const db = admin.firestore();
var data = {
Bitcoins : '0',
Ether : '0',
deyaCoins : '0'
};
var docRef = db.collection('Samyata').doc(ID);
var updateDoc = docRef.update({
db.collection('Samyata').doc(ID).collection('Wallet').doc(ID).set(data);});
//var updateRef = docRef.update();
});//end of onCreate()
Try this :)
return db.collection('Samyata').doc(ID).collection('Wallet').doc(ID).set(data);
or you can concatenate the path like this
return db.collection(`Samyata/${ID}/Wallet/${ID}`).add(data)
transactionData= {
TimeStamp: "123",
SomeBooleanValue: false
}
var addDocToNewCollResult= admin.firestore().collection('CollectionLevel1').doc(userID).collection('CollectionLevel2').doc(transactionID).collection('CollectionLevel3').doc("OtherID").set( transactionData );

Resources