How to solve nested async database calls in Firebase Functions [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to get a list of objects and for each object there is a record in another collection which has to be called also. Both requests return promises and my question is, how to "wait" for the inner promises to be fulfilled before the next outer promises are done.
This is the code:
export async function getAllCompanies(req: Request, res: Response) {
try {
const listCompanies = await db.collection('companies').get()
const companies = listCompanies.docs.map(async doc => {
const data = doc.data()
const location = await db.collection('locations').doc(data.locationId).get()
const locationData = location.data()
return {
id: doc.id,
name: data.name,
address: locationData ? locationData.address : null,
zipCode: locationData ? locationData.zipCode : null,
city: locationData ? locationData.city : null,
country: locationData ? locationData.country : null,
email: data.email,
phoneNumber: data.phoneNumber,
type: data.type,
createTime: doc.createTime.toDate(),
lastUpdateTime: data.lastUpdateTime
}
})
return res.status(200).send({ companies })
} catch (err) {
return handleError(res, err)
}
}

I think you're looking for:
const resolvedCompanies = await Promise.all(companies);
return res.status(200).send({companies: resolvedCompanies});
just before the return res.status(...). This will wait for all of the promises you map-ed into the list of companies to resolve before returning and return the values instead of the promises.

Related

_query is not a function. (In '_query((0, _database.ref) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 15 hours ago.
Improve this question
I am getting an Error when using database _query
Error
ERROR TypeError: _query is not a function. (In '_query((0, _database.ref)(_FirebaseConfig.database, 'users'), (0, _database.orderByChild)('email'), (0, _database.equalTo)(email))', '_query' is undefined)
code:
(note that query is not being highlighted as used )
import { ref, get, set, orderByChild, equalTo, query } from 'firebase/database';
useEffect(() => {
const writeToDatabase = () => {
const email = UserDataFromGoogleAuth.email;
if (email) {
const query = query(ref(database, 'users'), orderByChild('email'), equalTo(email));
get(query)
.then((snapshot) => {
const uuid = snapshot.exists() ? Object.keys(snapshot.val())[0] : uid();
const userRef = ref(database, `/users/${uuid}`);
const userData = {
id: uuid,
name: UserDataFromGoogleAuth.displayName,
email: email,
profilePicture: UserDataFromGoogleAuth.photoURL,
};
return set(userRef, userData);
})
}
};
writeToDatabase();
}, [location, UserDataFromGoogleAuth, props.online, database]);
**
"firebase": "^9.17.1",**
I am getting an Error when using database _query
On this line:
const query = query(ref(database, 'users'), orderByChild('email'), equalTo(email));
You define a variable called query and then try to assign it a value based on calling that same uninitialized variable because it shadow's the query method you are importing from the firebase/database library.
Rename the variable to something else to prevent shadowing the imported method.
const usersWithMatchingEmailQuery = query(ref(database, 'users'), orderByChild('email'), equalTo(email));
get(usersWithMatchingEmailQuery)
.then(/* ... */)
Note: Don't forget to add a catch() to that Promise chain to handle errors.

Is there any way to display data from Firebase Firestore as a React Table? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 days ago.
Improve this question
Is it possible to display data from Firebase Firestore in a React Table?
I tried several approaches, but none worked. I tried map function and listing them by creating a custom React element by providing the data using props.
Expectation:
My Expectation
I want to display the user email, UID, and password as a table.
My Code:
let data = [];
// creating an user
const createUser = () => {
let email = prompt("Enter the user's email: ");
let password = prompt("Enter the user's password: ");
let collectionName = `${window.localStorage.getItem("user-email")}_auth-details#BESTCLOUD`;
password = MD5(password);
db.collection(collectionName).add({
email: email,
password: password
}).then(function (docRef) {
alert("Successfully created!")
console.log("UID", docRef.id);
db.collection(`${window.localStorage.getItem("user-email")}_auth-details#BESTCLOUD`).onSnapshot((snapshot) => {
let x = snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
for (let i = 0; i < 5; i++) {
data.push({
email: x[i].data.email,
id: x[i].id,
num: i
});
console.log(data)
}
});
})
.catch(function (error) {
console.error("Error: ", error);
});
};
If I do this, data is
[
{
"id": "fMrLCDCkUqsV8BcoFcNY",
"data": {
"email": "peter123#gmail.com",
"password": "e7e761c4d399a441c6469a7c0626ac2d"
}
}
]

Error put array in firebase with clouds functions [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I got this error when I created api for update but it has array data in it. i am using cloud functions in firebase cli
i use the code below
app.put("/api/update/blog/:id", (req, res) => {
(async () => {
try {
const reqDoc = db.collection("blogdetails").doc(req.params.id);
await reqDoc.update({
title : req.body.title,
author : req.body.author,
kategori : req.body.kategori,
paragraf : req.body.paragraf,
image : req.body.image,
});
return res.status(200).send({ status: "Success", msg: "Data Updated" });
} catch (error) {
console.log(error);
res.status(500).send({ status: "Failed", msg: error });
}
})();
});

I get an error "';' expected.ts(1005)" not even using TS? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Can anyone explain what is the problem here?
I'm not even using TS this is just javascript
async addChat(message) {
const now = new Date()
const chat = {
message,
username: this.username,
room: this.room,
created_at: firebase.firestore.Timestamp.fromDate(now)
}
const response = await this.chats.add(chat)
return response
}
I'm sorry, dumb mistake, this was outside of my class
class Chatroom {
constructor(room, username) {
this.room = room
this.username = username
this.chats = db.collection('chats')
}
async addChat(message) {
const now = new Date()
const chat = {
message,
username: this.username,
room: this.room,
created_at: firebase.firestore.Timestamp.fromDate(now)
}
const response = await this.chats.add(chat)
return response
}
}
The issue is with your function declaration. You need to either do this
async function addChat() {
....
}
or
addChat = async () => {
....
}

Parsing error Javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Getting a parsing error in javascript while deploying firebase functions... Its showing unexpected token which if i'm not mistaken means that there is an unexpected character somewhere... Stuck here for weeks now... Can somone help me out please
Code
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref(`/Notifications/${user_id}/${notification_id}/`).onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to ', user_id);
if (!change.after.val()) {
return console.log("A Notification has been deleted from the database", notification_id);
}
const fromUser = admin.database().ref('/Notifications/${user_id}/${notification_id}').once('value');
return fromUser.then(fromUserResult => {
const fromUserId = fromUserResult.val().from;
console.log('You have a new notification from : ', from_user_id);
const userQuery = admin.database().ref('UserData/${fromUserId}/name').once('value');
return userQuery.then(userResult => {
const userName = userResult.val();
const deviceToken = admin.database().ref(`/UserData/${user_id}/TokenID`).once('value');
return deviceToken.then(result => {
const token_id = result.val();
const payload = {
notification: {
title: '${userName}',
body: "You have recieved a new Message",
icon: "default",
click_action: "com.appmaster.akash.messageplus_TARGET_NOTIFICATION"
},
data: {
from_user_id: fromUserId,
from_user_name: userName
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
return console.log('This was the notofication Feature');
});
});
});
});
You're missing two pairs of }) at the end of the file. So:
...
return admin.messaging().sendToDevice(token_id, payload).then(response =>{
return console.log('This was the notofication Feature');
});
});
});
});
});
It is understandably impossible to see this with your current code.
The lack of indentation makes it incredibly hard to parse. That's why I passed the code through http://jsbeautifier.org/, which makes it much easier to parse.
I also recommend using a tool like https://eslint.org/demo/ to make it easier to find mistakes like this.
you'll still have few bugs in your code. on three places you're using single quote ' instead of back-tick `
...
const fromUser = admin.database().ref(`/Notifications/${user_id}/${notification_id}`).once('value');
...
const userQuery = admin.database().ref(`UserData/${fromUserId}/name`).once('value');
...
const payload = {
notification: {
title: `${userName}`,
body: "You have recieved a new Message",
icon: "default",
click_action: "com.appmaster.akash.messageplus_TARGET_NOTIFICATION"
},
data: {
from_user_id: fromUserId,
from_user_name: userName
}
};

Categories