Firestore + cloud functions: How to read from another document - javascript

I'm trying to write a Google cloud function that reads from another document. (Other document = not the document that triggered the cloud function.)
It's a bit of a treasure hunt to figure out how to do such a simple thing.
The cloud functions documentation seems to suggest to look at the admin SDK: "You can make Cloud Firestore changes via the DeltaDocumentSnapshot interface or via the Admin SDK."
https://firebase.google.com/docs/functions/firestore-events
The Admin SDK suggest to write the following line of code to get a client. But oh no, it's not going to explain the client. It's going to send us off to a wild goose chase elsewhere in the documentation.
var defaultFirestore = admin.firestore();
"The default Firestore client if no app is provided or the Firestore client associated with the provided app."
https://firebase.google.com/docs/reference/admin/node/admin.firestore
That link resolves to a general overview page with no direct clue on figuring out the next thing.
https://cloud.google.com/nodejs/docs/reference/firestore/0.10.x/
Digging a big around, there is a promising class called FireStoreClient. It has a 'getDocument' method that seems promising. The parameter seems complicated. Rather than simply passing the path into the method, it seems to want an entire document/collection something as a parameter.
https://cloud.google.com/nodejs/docs/reference/firestore/0.10.x/FirestoreClient#getDocument
var formattedName = client.anyPathPath("[PROJECT]", "[DATABASE]", "[DOCUMENT]", "[ANY_PATH]");
client.getDocument({name: formattedName}).then(function(responses) {
var response = responses[0];
// doThingsWith(response)
})
So, I'm trying to combine all of this information into a Google cloud function that will read from another document.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.updateLikeCount4 = functions.firestore
.document('likes/{likeId}').onWrite((event) => {
return admin.firestore()
.getDocument('ruleSets/1234')
.then(function(responses) {
var response = responses[0];
console.log('Here is the other document: ' + response);
})
});
That approach fails with:
admin.firestore.getDocument is not a function
I've also tried. admin.firestore.document, admin.firestore.doc, admin.firestore.collection, and many more. None of them seem to be a function.
All I want is to read from another Firestore document in my Google cloud function.
PS: They said the documentation is your friend. This documentation is a nightmare that follows the principle of scatter all the clues into the four directions of the wind!

Thank you, #frank-van-puffelen.
This is the working solution:
exports.updateLikeCount = functions.firestore
.document('likes/{likeId}').onWrite((event) => {
return admin.firestore()
.collection('ruleSets')
.doc(1234)
.get()
.then(doc => {
console.log('Got rule: ' + doc.data().name);
});
});

Related

Can you call a Solidity contract method with only Metamask?

I’m wanting to use Metamask in my app to let users pay a fixed ETH fee (plus gas) to call a method from my Solidity contract. I looked at the Metamask documentation and the eth_sendTransaction method seems close to what I need; eth_sendTransaction would certainly allow me to request ETH from a user, but the “data” parameter is a bit confusing.
The Metamask docs say:
data is optional, but used for defining smart contract creation and interaction
and
also used for specifying contract methods and their parameters.
So “data” represents my method and its parameters, but how does Metamask (or window.ethereum, rather) know the contract whose methods I’m trying to call?
Don’t you normally have to provide a contract address and ABI/JSON in order to interact with a deployed contract? In short, is it possible to do what I’ve described with just Metamask alone? Or do you have to do other client-side setups in order to call a method with eth_sendTransaction?
Edit: by the way TylerH, the answer involved using web3.js. Maybe don't edit people's posts unless you know what the hell you're talking about. Just a thought...
Yes you will need the contract abi in order to get the information you need to include in the data that you're passing to the contract. There are also a few other things that you will need to accomplish this:
First you will need to make sure you download the ethers.js, and #alch/alchemy-web3 npm libraries into your application. Secondly you will need a provider API key from a platform like Alchemy in order to communicate with the contract abi. Lastly, you will need the contract abi which can be found at the bottom of the contract section of etherscan. There is plenty of information on how to obtain these things online, so I won't go over how to configure them here.
Once you have these, you are ready for the next step.
I suggest creating this in a utilities file somewhere in your applications file system, but the idea is this:
const alchemyKey = process.env.ALCHEMY_KEY;
const CONTRACT_ADDRESS = process.env.CONTRACT_ADDRESS;
const { createAlchemyWeb3 } = require("#alch/alchemy-web3");
const web3 = createAlchemyWeb3(alchemyKey);
const contractABI = require('../contract-abi.json');
export const contract = new web3.eth.Contract(contractABI, CONTRACT_ADDRESS);
export const yourMethod = () => {
if(window.ethereum.request({method: 'eth_requestAccounts'})){
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const address = await signer.getAddress();
const tx = {
from: address,
to: CONTRACT_ADDRESS,
value: "some wei value", // this is the value in wei to send
data: contract.methods.YOUR_CONTRACT_METHOD_HERE().encodeABI()
}
const txHash = await window.ethereum.request({
method: 'eth_sendTransaction',
params: [tx]
});
// do something with your transaction hash here
console.log({txHash});
}else{
console.log('user must connect wallet');
}
}
So the value that is populated in the data field of our transaction comes from calling the method that we are trying to invoke in our contract. This is encoded, and then we pass this information along with the rest of our transaction data.
This is a very short and brief description as to what this does, and I hope this is what you're looking for. If you need any more help I'm always available to chat on Twitter #_syndk8.

Firebase function not being triggered when data base is written to

My database is structured as follows Collection("Message").Document("message")
But in reality, I want any change in the database's main collection to be monitored—when a document is added. I added the message document because I thought that maybe the function wasn't being called since my documents are the auto-generated ones. However, the problem persists...
Just for background I am an iOS developer, so perhaps I am doing something wrong here:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendPushNotifications = functions.database.ref('/Messages/{message}').onCreate((snapshot,context) => {
console.log(snapshot);
console.log(context);
var topic = "/topics/sentMessages";
var payload = {
data: {
message : 'You recieved a new message!'
}
}
return admin.messaging().sendToTopic(topic,payload).then((response) => {
return response;
})
})
For additional background: The application receives push notifications fine when using the console whether it be directly to the testing device or using topics. This problem is strictly when writing to firebase Firestore...
When you said "Collection("Message").Document("message")" that suggested to me that you're using Firestore as your database. However, your function is targeting changes to Realtime Database, which is a completely different thing. functions.database builds function for Realtime Database. functions.firestore builds functions for Firestore. You will want to read the documentation on Firetore triggers to learn how to write them.

Get Every Document from inside a Users Collection Firebase

I have written a Firebase cloud function in which I want to get every users internal collection called 'numbers' and read each document out of that collection to do some comparisons.
Any idea how to do this?
I am pretty new to firebase and for some reason the database navigation commands are just not sticking with me very well.
I have tried a handful of commands with no success
const snapshot = functions.database.collection('users').collection('numbers').get()
let sfRef = db.collection('users');
sfRef.getCollections().then(collections => {
collections.forEach(collection => {
console.log('Found subcollection with id:', collection.id);
});
});
Here is a loose cloud code infastructure
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
export const prize1 = functions.pubsub.schedule('every 5 minutes').onRun((context) => {
const users = functions.database.ref('/users/numbers')
console.log("")
return null;
});
I feel like I have a good idea of how to do it, but the syntax is holding me back.
The collection of users. Go through each document in here, i.e. each user.
In each user go to the collection called numbers.
In the collection called numbers go through each document and find the numbers field to do logic/comparisons with.
Hopefully this can help you understand the way my database is ordered.
You could try it like this:
let usersRef = db.collection('users');
let allUsers = usersRef.get();
.then(userSnapshot => {
userSnapshot.forEach(userDoc => {
userDoc.ref.collection('numbers').get().then(numSnapshot => {
numSnapshot.forEach(numDoc => {
console.log(numDoc.data().numbers);
// here you got your numbers document with the numbers field
});
});
});
})
.catch((error) => {
console.log("Error getting document: ", error);
});
For more information you can look here and here.
You can't use functions for accessing the database. What you've defined as functions is for building triggers that respond to events. If you want to get data from Cloud Firestore, you should be using the Firebase Admin SDK via your admin instead. It might also help if you look through the official samples.
I will also point out that your code samples appear to be split between accessing Cloud Firestore and Realtime Database, which are different database products. Your screenshot shows Firestore, so ignore any APIs for Realtime Database.

Getting id of the current user from Cloud Functions and Firebase

I am using google cloud functions to register push notifications through firebase. In my app, i have a notifications reference that changes for a current user whenever they get a new follower or like, etc. As of right now I am able to send the notification to the phone whenever that whole reference child changes
For example, if any single post is liked, then it will send a notification. What I need to do is observe the current user to only send the notification that single person.
Here is my JavaScript file
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPushNotification = functions.database.ref('/notification/{id}').onWrite(event => {
const payload = {
notification: {
title: 'New message arrived',
body: 'come check it',
badge: '1',
sound: 'default',
}
};
return admin.database().ref('fcmToken').once('value').then(allToken => {
if (allToken.val()) {
const token = Object.keys(allToken.val());
return admin.messaging().sendToDevice(token, payload).then(response => {
});
}
});
});
I would like to replace this line:
functions.database.ref('/notification/{id}').onWrite(event => {
With this:
functions.database.ref('/notification/{id}').(The current user ID).onWrite(event => {
How do I get the current users id?
You seem very new to JavaScript (calling it JSON is sort-of a give-away for that). Cloud Functions for Firebase is not the best way to learn JavaScript. I recommend first reading the Firebase documentation for Web developers and/or taking the Firebase codelab for Web developer. They cover many basic JavaScript, Web and Firebase interactions. After those you'll be much better equipped to write code for Cloud Functions too.
Now back to your question: there is no concept of a "current user" in Cloud Functions. Your JavaScript code runs on a server, and all users can trigger the code by writing to the database.
You can figure out what user triggered the function, but that too isn't what you want here. The user who triggered the notification is not the one who needs to receive the message. What you want instead is to read the user who is the target of the notification.
One way to do this is to read it from the database path that triggered the function. If you keep the notifications per user in the database like this:
user_notifications
$uid
notification1: ...
notification2: ...
You can trigger the Cloud Function like this:
exports.sendPushNotification = functions.database.ref('/user_notification/{uid}/{id}').onWrite(event => {
And then in the code of that function, get the UID of the user with:
var uid = event.params.uid;
For Swift 3.0 - 4.0
You can do this:
import Firebase
import FirebaseAuth
class YourClass {
let user = Auth.auth().currentUser
let userID = user.uid
// user userID anywhere
}

Send FCM to all Android devices using Cloud Functions

Just trying to understand the process for sending a Firebase Cloud Message using Cloud Functions to notify all users who have my app installed on their phone. This would fire whenever a new event has been added at a particular branch, as follows:
var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const payload = {
notification: {
title: 'New event added'
}
};
exports.bookingsChanged = functions.database.ref("/Events")
.onWrite(event => {
return admin.messaging().sendToDeviceGroup("latest_events", payload);
});
The above function I've uploaded doesn't appear to send the message to the Android device I'm using at all, despite setting up and testing FCM using the Firebase Console option to send messages. I've noticed there is little documentation for this at the moment, so any help would be greatly appreciated!
EDIT
I may've missed this, but I've replaced the string 'latest_events' with my Android application package name that I assume is required, as per the console to target a 'User Segment'.
Ended up solving this by waiting for a topic I had set up to appear in the Firebase Notifications dashboard. I then changed the following code to send to this topic directly:
return admin.messaging().sendToTopic("latest_events", payload);
I also found out that you have to provide a token when using 'sendToDevicegroup' after coming across the API documentation. Therefore, topics are more effective in my use case as I do not wish to obtain tokens to send to specific user devices.
Hope this helps someone who experiences a similar problem!
ADDITIONAL EDIT
If like me, you would like to alert users only of new events that have been added to a specific branch, typically including a push id, I've created the following code to implement this.
With a little help from the examples in the documentation, this will evaluate the number of records at the location compared to the previous location. Thus, this will only alert users of new child records that are added, rather than every time a record is edited and deleted.
var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.bookingsChanged = functions.database.ref("/Bookings").onWrite(event
=> {
var payload = {
notification: {
title: "A new event has been added!"
}
};
if (event.data.previous.exists()) {
if (event.data.previous.numChildren() < event.data.numChildren()) {
return admin.messaging().sendToTopic("latest_events", payload);
} else {
return;
}
}
if (!event.data.exists()) {
return;
}
return admin.messaging().sendToTopic("latest_events", payload);
});

Categories