retrieve all customers email address stripe node.js - javascript

I have this function that tries to retrieve all the customer's emails in stripe:
const customers = await stripe.customers.list({
});
var customerEmail = customers.data[0].email;
console.log(customerEmail)
I am trying to return all the email addresses of the users from stripe. the problem is, when I log it, it only returns the first one, due to teh fact that I have data[0]. I need all of them, but i can't put it in a loop because what am i looping through. is there any way to do this properly?

The data property you are indexing is an array you can iterate through[1].
const customers = await stripe.customers.list({});
customers.data.forEach(customer => {
console.log(customer.email);
});
[1] https://stripe.com/docs/api/customers/list

Related

How to get value from firebase without the snapshot key [JS]

Im trying to make friends system but in invite accept i have to delete invite of a guy in his list but i cant do it without the key.
How do i get the snapshot key by value (in this case uid) in database?
Firebase Realtime Database queries work on single path, and then order/filter on a value at a fixed path under each direct child node. In your case, if you know whether the user is active or pending, you can find a specific value with:
const ref = firebase.database().ref("friends");
const query = ref.child("active").orderByValue().equalTo("JrvFaTDGV6TnkZq6uGMNICxwGwo2")
const results = query.get();
results.forEach((snapshot) => {
console.log(`Found value ${snapshot.val()} under key ${snapshot.key}`)
})
There is no way to perform the same query across both active and pending nodes at the same time, so you will either have to perform a separate query for each of those, or change your data model to have a single flat list of users. In that case you'll likely store the status and UID for each user as a child property, and use orderByChild("uid").
Also note that using push IDs as keys seems an antipattern here, as my guess is that each UID should only have one status. A better data model for this is:
friends: {
"JrvFaTDGV6TnkZq6uGMNICxwGwo2": {
status: "active"
}
}

How can I map a JavaScript array to save every element to a database and return the saved item?

I am working on an application that allows users to send an email to a list of contacts. Here is how the function that I am having trouble with works:
The email content is saved to the database.
The array of contacts is mapped. For every contact...
...The contact is saved to the database.
...An email is sent to the contact with a URL containing the email id and their contact id that the database generated.
...The saved recipient should be but is not currently returned.
The array of saved contacts which are currently just empty objects :( is returned to the front end.
An empty object is returned for every contact instead of the actual contact, which is weird because I can console.log() the object within the map, and the contact's information is being sent in the email, so it definitely exists at some point.
Here is the code:
const postOne = async (req, res) => {
const db = req.app.get("db");
const { adviceRequest, recipients } = req.body;
// ( Validation goes here )
try {
// Save the request.
let [savedRequest] = await db.requests.postOne([
adviceRequest,
req.session.user.id,
]);
// For every recipient...
let savedRecipients = recipients.map(async (person) => {
// ...Save them to the database.
let [savedRecipient] = await db.responses.postOne([
savedRequest.request_id,
person.email,
person.name,
req.session.user.id,
]);
// At this point, console.log(savedRecipient) shows the actual recipient, so it works.
// ...Send them an email.
await sendMail(savedRecipient, savedRequest);
// ...Then add the saved recipient to the array that .map() generates.
return savedRecipient;
});
// Send the request and the array of people back.
return res.status(200).json([savedRequest, savedRecipients]);
} catch (err) {
return res.status(500).json(err);
}
},
The thing is, the array that the .map() returns is an array of empty objects. I do not know why. Inside the .map(), savedRecipient is defined as it should be, and the information there is successfully being used to send the required information via email. But what is returned to the front end is an array of empty objects--one for each contact.
If someone could tell me what I am doing wrong, I would appreciate it!
You can try for loop to use async and await.
let savedRecipients = recipients.map(async (person) =>
Property savedRecipients here is an array of promises. Try to resolve this promises, like this:
const savedRecipientsData = await Promise.all(savedRecipients);

How to get image URL without downloading?

There is a way to download, like below:
const image = await storage.child('img/'+usrname+'.jpg').getDownloadURL();
this.setState({image});
But What I want?
I want to get image as directly, like below:
https://firebase.google.com/storage/img/#david.jpg
https://firebase.google.com/storage/img/#jack.jpg
https://firebase.google.com/storage/img/#harry.jpg
Why I want like above.
because I have a list of users with name, phone and username, there I saved the image of every user by his/her username(username.jpg).
Now when I list the users I used a loop, like below:
users = [];
for(let i=0; i<usersData.length; i++){
const user = {
name: usersData[i].name,
phone: usersData[i].phone,
image: 'https://firebase.google.com/storage/img/'+usersData[i].username
}
users.push(user);
}
Note:
Dont be confused about url (https://firebase.google.com/storage/) ,I just gave an example.
I don't think Firebase gives us direct link as this
https://firebase.google.com/storage/img/#david.jpg
https://firebase.google.com/storage/img/#jack.jpg
Because it does not include any project specific data (Like your storage bucket name, your project ID, token for authentication and so) in this form of URL. And if you think you will find that it increases the security to your files in the storage, as no-one can make a random guess to get the access to your storage data .
In your case you might have to go somewhat in this direction.
Here, we are first iterating through the userData list to aggregate all the promises using Promise.all after that in the then we get the list of resolved promises inside which our url for the image exists.
In last we set various property on our user object and push it to the users array.
users = [];
userPromise = Promise.all(
userData.map(data =>
firebase.storage()
.refFromURL('gs://<your bucket here>/img')
.child( data.username+'.jpg' ).getDownloadURL()
)
)
.then(ImgUrls =>{
ImgUrls.map((ImgUrl,i) => {
console.log(ImgUrl)
const user ={
name:userData[i],
phone: usersData[i].phone,
image: ImgUrl
}
console.log(user);
users.push(user);
});
});
console.log(users);

Saving a field from firestore that is an array

I am currently working on a mobile app on React and I am having trouble understanding how to save a field from fire store that is an array.
Since I can't post images my database structure is all strings such as username, first name, etc but I have a field called follow list that is an array.
What I want to do is save the usernames from the following list into an array to later search fire store for the username's in the array, this is basically what I want to do so I can render my app's social Feed. I do know that I can probably create another subcollection and write something familiar to what I did to search for users but that was a QuerySnapShot which was overall documents not a specific one and I also know firebase creates an ID for arrays and it increases as the array gets bigger.
I do not want to end up making two more subcollections one for followers and following which I think not ideal right? My current approach is this
export const fetchUserFollowing = async (username) => {
const ref = firebase.firestore().collection('users').doc(username)
let results = []
ref
.get()
.then( doc => {
let data = doc.data()
results = data
})
.catch((err) => {
return 'an error has occurred ', err
})
}
From what I understand is that a DocumentSnapShot .get() function returns an object but what I want is to store follow list into results and then return that but I am not sure how to manipulate the object return to just give me follow List which is an array
https://rnfirebase.io/docs/v5.x.x/firestore/reference/DocumentSnapshot
link to docs

fiirebase result.val is null with await

What is the response structure of firebase queries? Is there any documentation? I couldn't find anything. I don't why user is null below. Do I need to run for loop and get the first item?
const result = await firebase.child('users').orderByChild('email')
.equalTo(memberEmail).limitToFirst(1)
.once('value');
const user = result.val();
the following code works, but I don't want to run a loop to get single value. How do I get the user without running a loop?
result.forEach((value) => {
alert(`user = ${JSON.stringify(value.val())}`);
});
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result. So if you use a query, you will always need a loop.
The way to not require a loop is by directly accessing the child node that you are looking for. In your current data structure you likely store the users by their uid, so you can only access them directly by uid:
const result = await firebase.child('users').child(currentUser.uid).once('value');
const user = result.val();
If you'd store the users by their email address (you'll have to encode it, since a . cannot be used in the key), you could also access the users by their email address.
An idiomatic way to do this with Firebase is to keep a separate node that maps email addresses to uids. You'd then do two direct lookups:
firebase.child('emailToUid').child(email)
firebase.child('users').child(uid)
Each of those would return a single node (or no node if there is no match found), so you could chain the awaits and won't need a loop

Categories

Resources