Reputation: 61
When i need the current user id in the client side , I can use: firebase.auth().currentUser.uid
.
How can i get the current user id in cloud functions (Pub Sub trigger)?
exports.sendPushNotification = functions.pubsub.schedule("* * * * *")
.onRun(async (context) => {
const today = new Date();
const date = today.getFullYear()+"-"+(today.getMonth()+1)+
"-"+today.getDate();
const query = await db.collection("posts")
.where("date", "==", date)
.where("idUser", "==", i need here to call my current user id)
.get();
query.forEach(async (snapshot) => {
sendNotification(snapshot.data().idUser, snapshot.data().title);
});
});
Upvotes: 1
Views: 1267
Reputation: 50850
No, you cannot get any UID in a scheduled cloud function. That function is not invoked by a user. It's just being invoked periodically based on your schedule. The documentation says:
This field is only populated for Realtime Database triggers and Callable functions. For an unauthenticated user, this field is null. For Firebase admin users and event types that do not provide user information, this field does not exist.
The context object in this case looks something like this:
{
"eventId": "eventId",
"timestamp": "2021-05-16T09:21:00.505Z",
"eventType": "google.pubsub.topic.publish",
"params": {},
"resource": {
"name": "projects/<project-id>/topics/firebase-schedule-scheduledFunctionCrontab-us-central1",
"service": "pubsub.googleapis.com",
"type": "type.googleapis.com/google.pubsub.v1.PubsubMessage"
}
}
To get all users with due date passed you can use this query:
const snapshot = admin.firestore().collections("posts").where("data", "<=", Date.now()).get()
const userIds = snapshots.docs.map(post => post.data().idUser)
//Array of users IDs of posts with due date passed
Do note I have used UNIX Timestamp instead of the date as a string. Then you can performs actions for users with those UIDs as needed.
Upvotes: 2
Reputation: 1133
You can get user id from the following context.auth.id
in firebase functions.
const query = await db.collection("posts")
.where("date", "==", date)
.where("idUser", "==", context.auth.id) //something like this
.get();
Upvotes: 0