Firebase Cloud Firestore request - firebase

I have a MESSAGERECAP collection which includes a unique id for each message, the id of the receiver of the message, the id of the sender and the message itself. In my application, when the user clicks on a friend to chat with him, I want the chat activity to start with the list of messages they have both sent.
I did this but obviously it does not give the desired result :
Query query = messageRef.orderBy("mssgId",Query.Direction.DESCENDING);
// with messageRef a reference to the MESSAGERECAP collection
Here is an overview of my database

You are getting the whole list because you are not filtering the data, just ordering it. If you check the Querying documentation for Firestore, also provided by #FrankVanPuffelen on the comments of your question, you can see that you have to use .where() to filter the data that you want to retrieve.
Also, as pointed out by #Jay in the comments, you can use Compound Queries to create a logical AND on your query to retrieve the data you want.
So if you do something like:
messageRef.where("senderId", "==", [currentUserId])
.where("receiver_id", "==", [receiverUserId])
.orderBy("mssgId",Query.Direction.DESCENDING)
When you execute this query you will get all the messages sent by the current user to the receiving user of the correponding id.

Related

Firebase - Showing users that they have unread messages

I'm trying to determine the best way to handle showing the user that they have an unread message, in the navbar for example.
Currently I have separate documents for each conversation with data like so:
users: [ 'userId-1', 'userId-2' ]
messages: [
{
message: 'Test message',
timestamp: 12345678910,
userId: 123456
},
// etc...
]
Currently I'm thinking about adding an unread property to the message objects. Then, on page load, I would have to fetch each document where users contains the currentUser id and if any of the message objects in messages contains the unread: true property.
But then I would have to mark the message as read, but only for one of the users. So my data structure already doesn't work.
Also, this doesn't seem very performant to me, especially if the user has a great amount of conversations. Any idea on how to approach this differently?
I'm trying to determine the best way to handle showing the user that
they have an unread message, in the navbar for example
I understand that you only want to show a number of unread messages (or the information that there is a least one unread message). If this is the case you can get advantage of the new count() aggregation which takes into account any filters on the query.
Your data model is not 100% clear to me but since you have an Array of users, you could have an extra Array field containing the users that haven't read the message. So on page loading, you need to build the query of all messages where this array contains the currentUser uid and then call getCountFromServer() on this query.
Instead of being charged for each message that corresponds to the query you'll be charged one document read for each batch of up to 1000 index entries matched by the query.

Limit the retrieve of documents from Firebase on Flutter

I would like to learn how can I limit the retrieved document from Firestore quantity for each user. Is there any possible way to achieve this with shared preferences? Because I do not use a login or registration protocol for the user. I am using shared preferences in order to recognize the user.
Single user should retrieve only 1 document each day. This is what I want to implement.
Also I would like to learn that how can I save and show fetching date of the document?
You can do the following in Firebase:
Query query = cities.orderBy("name").limit(3); // descending order
Query query = cities.whereGreaterThan("population", 2500000L).orderBy("population").limit(2); // ascending order
You can take a look at the documentation, there are the corresponding methods.
https://firebase.google.com/docs/firestore/query-data/order-limit-data

How to write to a document and read the id of it within a single transaction in Firestore?

I am doing the user authentication where I have this case:
Read from vendor_type document and if it returns null(doesn't exist) then continue the transaction,
Create new user using .auth().createUserWithEmailAndPassword(email,password),
Read the new users ID,
Write to vendor_type document some of the new user's detail such as name, surname, userId -->> userId is the problem, how can I create a user and get the ID within a single transaction, can I even do that? ,
Take the newly created ID of the user, and create a new vendor document with that ID.
So far I don't have any code to post because I don't know if this is even gonna work so I didn't start. If you have any idea how to implement this, please let me know. The main issue is getting the user ID while still in the transaction.
At the time of writing, it is not possible to combine in one transaction the creation of a user through the createUserWithEmailAndPassword() method from the Auth service AND a write to the Firestore service.
They are two different services offered by Firestore and therefore you cannot combined calls to these two different services in one transaction.

How to get field ref data in firebase in single call?

I have below firestore collections.
-Converstions(collection)
(document) {participants: {userid1: true, userid2: true}, messages: [subcollection]}
-Users(collection)
(document)(userid1){userName: 'Test1', ...}
(document)(userid2){userName: 'Test2', ...}
Now I need to query for conversations a users is in, I can do this with
firebase.firestore().collection('conversations')
.where(`participants.${uid}`, '==', true);
What this does is gets all conversation a users is participating in, I need to now get the user details from id for each document in those conversation. If we make another call to UserRef to get the user details it will make extra request for each conversation data. I wanted to know if there is easy way to get user details in single call to the firebase.
When a user is added to a document, you could also add some display information about that user (either from the app or Cloud Functions).
There is no way to return data referenced elsewhere. You either need to duplicate or make multiple fetches.

How to fetch email marketing insights data from Marketo using API?

I am trying to fetch "Email Performance Report" from the platform
using API to analyze the KPI's like CTR etc by type of the email
(newsletter,email marketing etc).
I went through the documentation, however I didn't find endpoint from
which I can fetch the same.
Does anyone know if there is a way to get this information?
There is no endpoint to query reports directly. However, the good news is, that the “things” that make up an “Email Performance Report”, namely: email delivery, bounce, open and click are available to query via the API.
This means that you have to build the report yourself, but you can fetch the dataset to work on.
These “things” are called activity types (activity measured on a Lead) and can be fetched by querying against the Get Lead Activities endpoint, which is also mentioned as the Query in the API docs.
It sits at the GET /rest/v1/activities.json url and you have to pass a nextPageToken and the activityTypeIds as query parameters.
The nextPageToken indicates a datetime. Activities after that date will be returned by the call. To obtain one, you have to make a call to GET /rest/v1/activities/pagingtoken.json, where you have to specify the earliest datetime to retrieve activities from. See more about Paging Tokens.
To figure out the value of activityTypeIds, you first need to get the internal Ids of the activity types you are interested in. In order to do so, you have to query the GET /rest/v1/activities/types.json endpoint and look for the activity types with names like Send Email, Email Delivered, Email Bounced, Unsubscribe Email, Open Email and Click Email. (I don't know if these Ids are changing from instance to instance, but in ours these are from #6 to #11).
Once you have all of these bits at hand, you can make your request like that:
GET https://<INSTANCE_ID>.mktorest.com/rest/v1/activities.json?activityTypeIds=<TYPE_ID>&nextPageToken=<NEXTPAGE_TOKEN>&access_token=<ACCESS_TOKEN>
The result it gives is an array with items like below. Items can be filtered to specific email based on the primaryAttributeValue property and processed further accordingly.
{
"id":7370416,
"marketoGUID":"7170506",
"leadId":291305,
"activityDate":"2017-12-17T00:00:00Z",
"activityTypeId":11,// #11 = `Click Email`
"campaignId":1790,
"primaryAttributeValueId":1638,
"primaryAttributeValue":"EMAIL_NAME",// Name of the Email as seen in Marketo
"attributes":[
// …
]
}

Resources