How i can read multiple child from database Firebase using DialogFlow? - javascript

I'm having trouble reading Firebase 'real database' data.
I created an intent with the parameter $nomeProf. When I pass a value and try to query in db a "Webhook call failed occurs.
Error: 500 Internal Server Error
Access to database is working, I just can't read the children.
I'm trying to get the email pass unique id in dialogflow consoles, example:
'qual o email do faria?', $nomeProf=faria.
'faria' and 'correa' are my unique like ID:
function getProfessorHandler (agent){
//let nomeProf = agent.parameters.nomeProf; #I need something like this?
return admin.database().ref("Professor").once('value').then((snapshot) => {
const value = snapshot.child("nomeProf").val();
const email = value.email;
if(value !== null){
agent.add(`O email é: ${email}`);
}
});
}

It sounds like you want to load a single child of Professor from the database, based on the agent.parameters.nomeProf value.
That'd be something like this:
return admin.database().ref("Professor").child(agent.parameters.nomeProf).once('value').then((snapshot) => {
const value = snapshot.val();
const email = value.email;
if(value !== null){
agent.add(`O email é: ${email}`);
}
});

Related

Mongo db query , take any userinput and search according to those

I’m new to mongo DB. What will be the schema or schemas what is user inputted, how we can recognize those in our code, or rather what will be the query (using javascript ).
Question:
Suppose we have a book schema and saved some books in the database, now we have to make a post api /getParticularBooks
take any input and use it as a condition to fetch books that satisfy that condition
e.g
if body had { name: “hi”} then you would fetch the books with this name
if body had { year: 2020} then you would fetch the books in this year
Or maybe the both at same time
hence the condition will differ based on what you input in the request body
You can start by creating a function which verify if the user request body doesn't have any input property which isn't define in your schema.
I would do it like that
const verifyProperty = (user_request_body) => {
const properties = [list of your schema property];
for(let i in properties){
const string = properties[i]
if(!(string in user_request_body))
return false;
}
return true;
}
And now, based on the return value of the verifyProperty function, you can send a query or return an error message.
if(verifyProperty(req.body) == false){
return res.json({message: "Invalid properties"})
}
const data = await Books.find(req.body);
return res.json({data})
In order to use await, your function must be async

How can I check If a message exists in discord.js

I would like to have some kind of reaction roles into my bot. For that I have to test If the message ID that the User sends to the bot is valid. Can someone tell me how to do that?
You can do that with .fetch() as long as you also know what channel you're looking in.
If the message is in the same channel the user sent the ID in then you can use message.channel to get the channel or if it's in another channel then you have to get that channel using its ID using message.guild.channels.cache.get(CHANNEL_ID).
So your code could be like this if it's in the same channel:
const msg = message.channel.messages.fetch(MESSAGE_ID)
or if it's in a different channel:
const channel = message.guild.channels.cache.get(CHANNEL_ID)
const msg = channel.messages.fetch(MESSAGE_ID)
This works for me (Discord.js v12)
First you need to define the channel where you want your bot to search for a message.
(You can find it like this)
const targetedChannel = client.channels.cache.find((channel) => channel.name === "<Channel Name>");
Then you need to add this function:
async function setMessageValue (_messageID, _targetedChannel) {
let foundMessage = new String();
// Check if the message contains only numbers (Beacause ID contains only numbers)
if (!Number(_messageID)) return 'FAIL_ID=NAN';
// Check if the Message with the targeted ID is found from the Discord.js API
try {
await Promise.all([_targetedChannel.messages.fetch(_messageID)]);
} catch (error) {
// Error: Message not found
if (error.code == 10008) {
console.error('Failed to find the message! Setting value to error message...');
foundMessage = 'FAIL_ID';
}
} finally {
// If the type of variable is string (Contains an error message inside) then just return the fail message.
if (typeof foundMessage == 'string') return foundMessage;
// Else if the type of the variable is not a string (beacause is an object with the message props) return back the targeted message object.
return _targetedChannel.messages.fetch(_messageID);
}
}
After this procedure, just get the function value to another variable:
const messageReturn = await setMessageValue("MessageID", targetedChannel);
And then you can do with it whetever you want.Just for example you can edit that message with the following code:
messageReturn.edit("<Your text here>");

Using multiple conditions in firebase rules and accessing with if statement not working

I have multiple conditions in my firebase rules and want to access the data base on the current user by using if statement in my return statement. When I access it individually, it works but when I use if statements, I don't get the data but permission error issue.
I've tried accessing it but keeps failing.
My rule:
"query.orderByChild == 'userId' && query.equalTo == auth.uid ||
root.child('admins').child(auth.uid).child('role').val() === 'admin'"
Accessing the data:
let db = firebase.database().ref(`/items`).orderByChild('userId').equalTo(currentUser.uid)
if(firebase.database().ref('/admins').child(currentUser.uid).child('role').equalTo('admin')) {
db = firebase.database().ref(`/items`)
}
db
.once('value')
.then(snapshot => {
let doc = []
const data = snapshot.val();
for (let key in data) {
doc.push({
...data[key],
key: key
});
}
Ideally, I would like to have a rule with OR and have an if/else statement to return data depending on the user.
This statement does not do what you think it does:
if(firebase.database().ref('/admins').child(currentUser.uid).child('role').equalTo('admin'))
Nothing in this line reads from the database, and the equalTo merely builds a query, it does not actually perform any check.
If you want to to check whether the user is an admin:
let userRoleRef = firebase.database().ref('/admins').child(currentUser.uid).child('role');
userRoleRef.once('value').then((snapshot) => {
if ('admin' == snapshot.val()) {
db = firebase.database().ref(`/items`)
... continue using db here
}
}
Now the client-side query and the server-side security rules work in tandem to ensure the user only requests and only can get the data that they're authorized for.

FireStore : How to update Field in object data structure in firestore using cloud functions

I Stored the data in object form and I want to add or update one filed like "Status" into each object like invitee1 and invitee2 using cloud functions.I tried but it is updated at the end of all the objects. How to add the field at the end of each object using cloud functions or Firestore triggers. I am getting this type of error when I use update statement
var dbref = db1.collection('deyaPayUsers').doc(sendauthid).collection('Split').doc(sendauthid).collection('SentInvitations').doc(senderautoid);
var msg1 = receiverph +"" + status +" to pay $"+document.Amount;
var fulldoc = dbref.get()
.then(doc => {
if(!doc.exists){
console.log('No such document');
}else{
console.log('Document data :',doc.data());
d1 = doc.data();
console.log("d1 is"+d1);
for(var k in d1){
var p = d1[k].PhoneNumber;
console.log("ivitees phone"+p);
if(receiverph == p)
{
console.log("p"+PhoneNumber);
console.log("the phonenumber matches");
var updated = dbref.p.update({"Status":status});// **i got error here like "update is not define"**
i tried another way to update
var updated = dbref.d1[k].PhoneNumber.update({"Status":status});// here i got error like "Can not read property of invitee1 of undefined"
How to solve that error.
You can't update the field directly. Do like this:
With the document reference,
for(var k in d1) {
if (receiverph === d1[k].PhoneNumber) {
doc.ref.update({
[`${k}.Status`]: status
})
}
}

Retrieve data from Firebase database in JavaScript

I am new to Firebase, and I am trying to figure out how to retrieve data from my Firebase database. I was able to add to it successfully based on a user's unique id (uid), but now getting data from it seems to be incredibly difficult. I want to grab the first name from the current user ('user' in the following code), but this JavaScript doesn't seem to be working:
var uid = user.uid
firebase.database().ref('users/' + uid).on('value', function(snapshot) {
this.first_name = snapshot.val().first_name;
});
As soon as I make the call to this.first_name, it gives me the following error:
FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot set property 'first_name' of null.
In case it helps, my database is structured like this:
{
users: {
"uid1": {
first_name: "John"
},
"uid2": {
first_name: "Sue"
}
}
}
Use var first_name instead of this.first_name. It should work.
var uid = user.uid
firebase.database().ref('users/' + uid).on('value', function(snapshot) {
var first_name = snapshot.val().first_name;
});
The answer above is correct. but, i guess it's more readable if you use child in the query. Both should work.
firebase.database().ref('users').child(uid).on('value', function(snapshot) {
var first_name = snapshot.val().first_name;
});

Categories

Resources