I have a messages entry that looks like this:
firbaseapp
messages
-KiG85eYMH7jfKph4bl3
created: 1492788734743
title: "title"
message: "message"
I want to send a notification when new entries are added to this list so
I added this cloud function:
exports.sendMessageNotification = functions.database.ref('/messages/').onWrite(event => {
event.data.forEach(message => {
if (message.val().notificationSent) {
return;
}
admin.messaging().sendToTopic(...)
.then(res => {
return db.ref('/messages').child(message.key).update({
notificationSent: (new Date()).getTime(),
});
})
});
});
Problem is message.key is messages-KiG85eYMH7jfKph4bl3 so when I try to save it, it creates a new entry instead of updating the existing one:
firbaseapp
messages
-KiG85eYMH7jfKph4bl3
created: 1492788734743
title: "title"
message: "message"
-messages-KiG85eYMH7jfKph4bl3
notificationSent: 123434554534
What I wanted is for notificationSent to be set on the existing entry.
I also tried using message.ref but I get the same result.
So what is the best way to update a list item in firebase in a cloud function?
I think this accomplishes what you want to do and also answers your questions in the comments:
exports.sendMessageNotification = functions.database.ref('/messages/{messageId}')
.onWrite(event => {
const messageId = event.params.messageId;
console.log('messageId=', messageId);
if (event.data.current.child('notificationSent').val()) {
console.log('already sent');
return;
}
const ref = event.data.ref; // OR event.data.adminRef
admin.messaging().sendToTopic(...)
.then(res => {
return ref.update({
// Caution: this update will cause onWrite() to fire again
notificationSent: (new Date()).getTime(),
});
})
});
Related
I am a react-native developer and new to firebase. I am performing firebase realtime database operation, have a look at code below;
firebase.database().ref('events/wedding/items').push(object).then((data) => {
//success callback
dispatch(addPendingInvoice({ ...invoice, id: data.key }))
Alert.alert('Successfully added to Invoices', 'Please go to invoice section to clear first and continue.', [{ text: 'Ok' }])
}).catch((error) => {
//error callback
Alert.alert("Can't book package.", 'Please check your internet connection!', [{ text: 'OK', style: 'destructive' }])
})
Now, I wish to push another object to another node events/wedding/packages right after this firebase database function above. I can use another function inside then callback in above firebase functions. This is not a professional way to do this.
Is there any way to do this?
You can use the update() method to "simultaneously write to specific children of a node without overwriting other child nodes". Note that "simultaneous updates made this way are atomic: either all updates succeed or all updates fails", see the doc.
So in your case you would do along the following lines:
var newNodeKey = firebase.database().ref().child('events/wedding/items').push().key;
var updates = {};
updates['events/wedding/items/' + newNodeKey] = { foo: "bar" };
updates['events/wedding/packages/' + newNodeKey] = { bar: "foo" };
firebase.database().ref().update(updates)
.then(() => {
// The two writes are completed, do whatever you need
// e.g. dispatch(...);
});
All Firebase operations return a promise so you can use Promise.all() to run them all simultaneously.
Promise.all([
firebase.database().ref(reference).set({}),
firebase.database().ref(reference2).set({})
]).then(() => {
console.log("Operations Successful")
}).catch((e) => console.log(e))
You can also push all your operations to an array and then pass that array in Promise.all()
With Realm sync of MongoDB, I'm trying to launch a trigger when a realm user is created to insert his newly created ID into my cluster. Here's the javascript function I made that is being called by the trigger :
exports = async function createNewUserDocument({ user }) {
const users = context.services
.get("mongodb-atlas")
.db("BD")
.collection("patients");
const query = { email: context.user.data.email };
const update = {
$set: {
patientId: context.user.id
}
};
// Return the updated document instead of the original document
const options = { returnNewDocument: true };
console.log(context.user.data.email);
return users.findOneAndUpdate(query, update, options)
.then(updatedDocument => {
if(updatedDocument) {
console.log(`Successfully updated document: ${updatedDocument}.`)
} else {
console.log("No document matches the provided query.")
}
return updatedDocument
})
.catch(err => console.error(`Failed to find and update document: ${err}`))
};
When running from the embed editor, while specifying the proper user manually, it's working perfectly. However, when launched by the trigger, it looks like the user is the system user and not the created user, because the error I get in the logs is the same I get when I run from the editor by specifying System user, which is Failed to find and update document: FunctionError: cannot compare to undefined. This makes sense because the System user is not a user per se, so the context.user is undefined.
I find it weird since I specify in the function settings that it should be executed with the permissions of the user calling the function. So my question is, is it possible to access the user.context of a user on his creation, and if so, how would I do it ?
I am utilising a Firebase Realtime Database with the below structure.
I wish to fetch all "notes" a user has access to and subscribe to changes in those notes.
notes: {
"noteId-1345" : {
"access" : {
"author": "1234567890"
"members": {
"1234567890": 0 <--- Author
"0987654321": 1 <--- Member
}
},
"data" : {
"title": "Hello",
"content": "Konichiwa!",
"comment": "123"
}
}
}
( I am aware this structure could, ideally, be more flat. :) )
To fetch all notes a user has access to - I keep an additional user_notes node in the root:
Whenever I associate a user (update of members) with a note, I update both /notes/$noteid and /user_notes/$uid.
user_notes: {
"$uid": {
"noteId-1345": {
myHide: false,
mySortOrder: 0,
title: "Hello"
}
}
}
When fetching data I wish to set up subscription to all notes the user has access to.
I begin by fetching the ids for notes the user has access to and then attach listeners to subscribe to updates in each note.
const uid = getState().auth.uid
let collectedNotes = {}
...
database.ref(`user_notes/${uid}`).on('value', (myAccessSnaps) => {
myAccessSnaps.forEach((accessSnap) => {
const noteId = accessSnap.key
const privateData = {'personalData': {...accessSnap.val()}}
database.ref(`notes/${noteId}`).on('value', (noteSnap)=>{
const notData = noteSnap.val()
const fullData = { ...privateData, ...notData }
const note = {
id: noteSnap.key,
...fullData
}
collectedNotes[note.id] = note
...
})
}))
})
(Of course, I will need to use .off() to detach listeners before setting up new ones)
This is somewhat problematic since I have to attach one listener per note - and there could be hundreds of notes in the database.
Is this the most efficient approach? - It seems inefficient.
Is there a way to listen to ALL the notes a user has acess to in the /notes path with one listener? Or is my approaching altogether wrong? :)
Kind regards /K
After understanding that .on() does not return a promise - I became much easier to solve my problem.
Attaching a lot of .on() listeners did not make any sense to me.
The easiest approach for me was to:
1 - Update my access nodes with a time stamp updatedAt each time a note was updated
2 - Load initial data using .once() that returns promise,see code below.
3 - Set up separate subscription for when access nodes changes
let myPromises = []
database.ref(`user_notes/${uid}`).once('value', (myAccessSnaps) => {
myAccessSnaps.forEach((accessSnap) => {
const noteId = accessSnap.key
const privateData = {'personalData': {...accessSnap.val()}}
myPromises.push(
database.ref(`notes/${noteId}`).once('value', (noteSnap)=>{
const notData = noteSnap.val()
const fullData = { ...privateData, ...notData }
const note = {
id: noteSnap.key,
...fullData
}
collectedNotes[note.id] = note
...
})
)
}))
})
return Promise.all(myPromises)
.then(() => {
dispatch(setNotes(categories))
...
// Set up subscription after initial load
database.ref(`user_notes/${uid}`).on('value', (myAccessSnaps) => {
...
// Use access node listener only - gets updated by 'updatedAt'
database.ref(`notes/${noteId}`).once('value', (noteSnap)=>{
//Collect and dispatch data
Kind regards /K
Semi-new developer building a project using the MERN stack.
The app has two models, one for Users and one for Tournaments. Tournament model has an attribute called participants which is an array.
I wrote an Express backend route so that a User can register for Tournaments.participants[].
This looks like:
router.post('/:id', (req, res) => {
Tournament.findById(req.params.id)
.then(tournament => {
tournament.participants.push(req.body);
return tournament.save();
})
.then(savedTournament => res.json(savedTournament))
.catch(err => res.json(err));
});
However, a User can just keep clicking Sign Up and I'd have a bunch of duplicate users, so I'm trying to write a conditional that will disable Sign Up if the user is already in Tournament.participants[].
I tried writing a conditional inside the Express route using Array.includes(req.body) but couldn't hack it.
Looked something like
Tournament.findById(req.params.id)
.then(tournament => {
if (tournament.participants.includes(req.body) {
return res.status(400).json({ msg: "This user already signed up for this tournament" });
} else {
tournament.participants.push(req.body);
return tournament.save();
}
})
.then(savedTournament => res.json(savedTournament))
.catch(err => res.json(err));
I tried different variations as well, like if (tournament.participants.includes(!req.body)) then push(req.body), etc.
And I also tried just rendering a different button if the participants.includes(user) but I believe this should be done on the backend anyway.. I'm open to suggestions.
Can anyone help me out?
In general, you can't use the native comparison operators with objects, includes included:
const foo = { id: 1 };
const bar = [{ id: 1 }];
console.log(bar.includes(foo)); // outputs `false`
You should use some kind of item id in order to check if its already exists:
function isIdIncluded(arr, id) {
return arr.some(x => x.id === id)
}
const foo = { id: 1 };
const bar = [{ id: 1 }];
console.log(isIdIncluded(bar, 1)); // outputs `true`
I assume you are keeping the users's _id in the participants array, and your tournament schema is similar to this:
const tournamentSchema = new mongoose.Schema({
name: String,
participants: Array,
});
Now if you send a request with this body:
{
"user": "5e97255a342f395774f30162" //the user id who wants to participate
}
You can use this code (I just changed the req.body to req.body.user)
Tournament.findById(req.params.id)
.then((tournament) => {
if (tournament.participants.includes(req.body.user)) {
return res.status(400).json({ msg: "This user already signed up for this tournament" });
} else {
tournament.participants.push(req.body.user);
return tournament.save();
}
})
.then((savedTournament) => res.json(savedTournament))
.catch((err) => res.status(500).json(err));
Now when a user first time participates a tournament, the document will be like this:
{
"participants": [
"5e97255a342f395774f30162"
],
"_id": "5e97255a342f395774f30161",
"name": "Chess Tournament"
}
And when the same user tries, the response will be like this with a 400 status code.
{
"msg": "This user already signed up for this tournament"
}
Also please note that, the user id shouldn't be send in the request body, but it must be the user's id who is logged in.
I am trying to transition the script from one state to another based on Smooch postback payloads; but getting error code H12.
Consider the example https://github.com/smooch/smooch-bot-example
Say I modify the script https://github.com/smooch/smooch-bot-example/blob/master/script.js as follows
start: {
receive: (bot) => {
return bot.say('Hi! I\'m Smooch Bot! Continue? %[Yes](postback:askName) %[No](postback:bye) );
}
},
bye: {
prompt: (bot) => bot.say('Pleasure meeting you'),
receive: () => 'processing'
},
The intention is that the's bot's state would transition depending on the postback payload.
Question is, how do I make that happen?
My approach was add
stateMachine.setState(postback.action.payload)
to the handlePostback method of github.com/smooch/smooch-bot-example/blob/master/heroku/index.js
However, that threw an error code H12. I also experimented with
stateMachine.transition(postback.action,postback.action.payload)
to no avail.
I got the same issue with the [object Object] instead of a string. This is because the state you get or set with a function is contained in an object, not a string... I fixed it with this code inside index.js, replacing the existing handlePostback function in the smooch-bot-example GitHub repo:
function handlePostback(req, res) {
const stateMachine = new StateMachine({
script,
bot: createBot(req.body.appUser)
});
const postback = req.body.postbacks[0];
if (!postback || !postback.action) {
res.end();
};
const smoochPayload = postback.action.payload;
// Change conversation state according to postback clicked
switch (smoochPayload) {
case "POSTBACK-PAYLOAD":
Promise.all([
stateMachine.bot.releaseLock(),
stateMachine.setState(smoochPayload), // set new state
stateMachine.prompt(smoochPayload) // call state prompt() if any
]);
res.end();
break;
default:
stateMachine.bot.say("POSTBACK ISN'T RECOGNIZED") // for testing purposes
.then(() => res.end());
};
}
Then inside script.js all you need to do is define states corresponding to the exact postback payloads. If you have multiple postbacks that should take the user to other states, just add them to the case list like so :
case "POSTBACK-PAYLOAD-1":
case "POSTBACK-PAYLOAD-2":
case "POSTBACK-PAYLOAD-3":
case "POSTBACK-PAYLOAD-4":
Promise.all([
stateMachine.bot.releaseLock(),
stateMachine.setState(smoochPayload), // set new state
stateMachine.prompt(smoochPayload) // call state prompt() if any
]);
res.end();
break;
Note that you should not write break; at the end of each case if the outcome you want is the same (here : setting the state and prompting the corresponding message).
If you want to handle other postbacks differently, you can add cases after the break; statement and do other stuff instead.
Hope this helps!
Postbacks won't automatically transition your conversation from one state to the next, you have to write that logic yourself. Luckily the smooch-bot-example you're using already has a postback handler defined here:
https://github.com/smooch/smooch-bot-example/blob/30d2fc6/heroku/index.js#L115
So whatever transition logic you want should go in there. You can do this by creating a stateMachine and calling receiveMessage() on it the same way handleMessages() already works. For example:
const stateMachine = new StateMachine({
script,
bot: createBot(req.body.appUser)
});
stateMachine.receiveMessage({
text: 'whatever your script expects'
})
Alternatively, you could have your handlePostback implementation call stateMachine.setState(state) and stateMachine.prompt(state) independently, if you wanted to have your postbacks behave differently from regular text responses.
If you want to advance the conversation based on a postback you'll have to first output the buttons from the bot's prompt (so you can handle the button click in the receive), modify the handlePostback function in index.js, then handle the user's "reply" in your receive method - try this - modify script.js like so:
start: {
prompt: (bot) => bot.say(`Hi! I'm Smooch Bot! Continue? %[Yes](postback:askName) %[No](postback:bye)`),
receive: (bot, message) => {
switch(message.text) {
case 'Yes':
return bot.say(`Ok, great!`)
.then(() => 'hi')
break;
case 'No':
return bot.say(`Ok, no prob!`)
.then(() => 'bye')
break;
default:
return bot.say(`hmm...`)
.then(() => 'processing')
break;
}
}
},
hi: {
prompt: (bot) => bot.say('Pleasure meeting you'),
receive: () => 'processing'
},
bye: {
prompt: (bot) => bot.say('Pleasure meeting you'),
receive: () => 'processing'
},
Then modify the handlePostback function in index.js so that it treats a postback like a regular message:
function handlePostback(req, res) {
const postback = req.body.postbacks[0];
if (!postback || !postback.action)
res.end();
const stateMachine = new StateMachine({
script,
bot: createBot(req.body.appUser)
});
const msg = postback;
// if you want the payload instead just do msg.action.paylod
msg.text = msg.action.text;
stateMachine.receiveMessage(msg)
.then(() => res.end())
.catch((err) => {
console.error('SmoochBot error:', err);
res.end();
});
}
Now when a user clicks your button it will be pushed to the stateMachine and handled like a reply.