Storing application start and end time in GCP Firestore - firebase

In one of my projects, I want to store application start time and end time to GCP Firestore in timestamp format.
I have tried the following things
I tried to save the java DateTime but in the Firestore its storing
as array(Firestore screenshot).
and also I tried to use the FieldValue but it's storing start time and end time as the same.
is there any way I can store time stamp in GCP Firestore with the actual time difference(application start time and end time)
I am storing the below model class by updating the completeAt and startedAt fields(note: I have tried with type FieldValue as well instead of Date).
public class Test{
private Date completeAt
private Date completeAt
}

Regarding the first attempt, completeAt it's not an array, it's an object.
Regarding your second attempt:
Is there any way I can store time stamp in GCP Firestore with the actual time difference(application start time and end time)
Both fields completeAt and startedAt are populated with the correct data type. However, the values are not correct. If you want the startedAt field to hold a Timestamp value when the app starts, then you should perform an update operation right then. As soon as the user stops using the app, perform another update the add the corresponding Timestamp to the completeAt field. In this way, you'll have different values for each field.

Related

DynamoDBAutoGeneratedTimestamp CREATE strategy is always updating?

I am trying to use the DynamoDBAutoGeneratedTimestamp annotation for generating timestamps for when my records are last updated and when they are created. The annotation currently has 2 strategies, ALWAYS and CREATE.
My initial understanding was that the ALWAYS strategy should update the timestamp every time the record is changed, and the CREATE strategy should set the timestamp only when the record is created. The ALWAYS strategy appears to be working just fine in updating the timestamp each time the record changes; however, the CREATE strategy appears to be behaving exactly the same as the ALWAYS strategy (meaning the timestamp updates each time the record changes).
It is now my understanding that the CREATE strategy doesn't do that, and instead tells the record to generate a timestamp if you're going to write it to the database and the value of the field in the record to be written is null.
This causes the field with the CREATE strategy to always be updated if the record itself is ever updated.
So, are there any easy solutions to this? I could set it myself, of course, but I was wondering if there is some sort of option or config that is not known to me that would address this issue?
Example code:
#DynamoDBTable(tableName = "Foo")
public class Foo {
#DynamoDBAutoGeneratedTimestamp(strategy = DynamoDBAutoGenerateStrategy.CREATE)
private Date createdAt;
#DynamoDBAutoGeneratedTimestamp(strategy = DynamoDBAutoGenerateStrategy.ALWAYS)
private Date updatedAt;
}

Firebase cloud function timestamp

In my current application, I store a value in Firestore for each user something along the lines of this:
User1Doc - hasUsedFeatureToday = true
User2Doc - hasUsedFeatureToday = false
...
At the end of the day, I run a scheduled function that resets all of these to false. This was fine while my application was relatively small, but does not scale very effectively as I'm sure you can imagine.
Each user can only use this aspect of my app once per day, so the only time this field is read is when they try to use it.
I would like to change this system to store a timestamp in the user's document when they use the feature and then check if this timestamp is the same day (Europe/London time) if someone tries to use it again.
Does Firebase offer a way to get a "timezoned" timestamp like this and store/check it with the Firestore?
You can just store a timestamp (UTC). Whenever users logs in to your app, just check the timestamp and update the same. You can always use libraries like Luxon to get local time from the UTC time.
If you want to allow the user to update this timestamp only once, you can use security rules to restrict the same. However, user may try to prevent the timestamp from being updated at first place.
You can instead use Cloud Function to serve the data only when the user requests it. This will be better than updating documents of all users even if they won't be using the feature every day.

Timestamp field in cosmos db

I am having a hard time using ts field in cosmos/document db with c#. Is it just better to create another date time field and use that instead of ts? How to decide when to use ts vs a custom date time field?
_ts represents a Unix Epoch and marks the time of the document's last modification. When a document is created, it has the creation time, but if later on the document is updated, then _ts is updated with that time.
Effectively it means the last modified time of the document.
It depends on your use case if you can use it or you need a custom date field. For example, if your intent it to track when a document was created, then you can't use it, as the value will change if the document is modified. If your intent is to track the last modified time, it can work (depends on the precision you need and if a Unix Epoch fills that requirement, otherwise you would need your own custom field).
Here is the official reference of system properties: https://learn.microsoft.com/azure/cosmos-db/account-databases-containers-items#properties-of-an-item

How to filter records by dateTime using firebase realtime database

In my firebase Realtime Database, every document saved has a datetime variable.
Example, dateTime:"2021-04-11T17:32:50.833523"
I have the following URL which fetches all documents. However, I now want to fetch only today's documents. I know that there are two options to achieving this. First one is to fetch all the documents from DB and then filter only today's records. Second option is to tweak the URL and put the filter while fetching records from the DB.
First I would like to know which approach yields faster results?
If it's the second approach, then I would like to know how to achieve it.
Here's the function I am using:
Future<void> fetchAllOrders() async {
final url ='https://fhgi-92211.firebaseio.com/orders.json?auth=$authToken';
}
According to the docs, something like this should work:
'https://fhgi-92211.firebaseio.com/orders.json?auth=$authToken&orderBy="dateTime"&startAt="2021-04-11"'
https://firebase.google.com/docs/database/rest/retrieve-data
Best solution - is n°2 : using & tweaking your URL - to do so I suggest :
First, tweaking your model by adding your date data in a simpler 2021-04-11 kinda of format
It will allow you much easier filtering
You can do so like this before writing your data to your RealTime Database :
import 'package:intl/intl.dart';
DateTime today = DateTime.now();
String simpleFormatToday = DateFormat('yyyy-MM-dd').format(today);
// returns a simple 2021-04-11 format of today's date
If your really need for some reason the full dateTime value you can write both dateTime:"2021-04-11T17:32:50.833523" & simpleDate:"$simpleFormatToday" to your object
Next,
To retrieve your data - use your function & tweak your URL to use Range Querying to retrieve only documents having simpleDate value equal to today - like so :
Future<void> fetchAllOrders() async {
final url ='https://fhgi-92211.firebaseio.com/orders.json?auth=$authToken&orderBy="simpleDate"&equalTo="$simpleFormatToday"';
}
First Approach
It will be useful if you want to get all the data and need to filter the dates several times from user input.
For example: If you have 100 records that you fetched using first approach i.e all you have is 100 records in your db and now user will make some filter on fetched records like getting 20-30 then 40-79, something like that. In this case making query using second approach wont be appropriate because of two reasons
Querying everytime on firebase would count read/write towards billing.
Managing data locally is more fast and reliable rather than making request to network frequently.
Second Approach
It will be useful in areas where you have to show specific time interval records in the one go and that's it, after fetching the records you dont need more of them to pull out from DB.
The Query will mainly revolve around what you want
equalsTo : It will give you only those records which will have exact date that you have passed as params.
orderBy : It will only work with equals to and will give you dates on bases of applied sorted filter (ex: by createdAt)
Future<void> fetchAllOrders() async {
//It will get today's date
var todaysDate = DateTime.now();
//From today's 12AM
var filterStartDate = DateTime(todaysDate.year,todaysDate.month,todaysDate.day,0,0,0);
//To second days' 11:59PM
var filterEndDate = DateTime(todaysDate.year,todaysDate.month,todaysDate.day,23,59,59);
final url ='https://fhgi-92211.firebaseio.com/orders.json?auth=$authToken&startAt="${filterStartDate.toIso8601String()}&endAt="${filterEndDate.toIso8601String()}';
}

How to trigger a cloud function when a date stored in a firestore doc property arrives

I'm building a multisided app where people can sell and buy food. Thats the shortest summarize possible.
When an user make a food order to a restaurant and this order has been marked as dispatched, the app generates a comission on the restaurant profile in firestore.
When the commission is created it triggers a background firebase cloud function that check if the restaurant has an active billing cycle, if not, it creates one like this:
billingCycle: {
openDate: 'the moment where the fee was created',
endDate: '4th day after' //
}
This object its created in the user profile (with correct date) and works ok!
Now I want to emit an invoice when the date of the endDate prop value arrives, here comes the question.
How can I trigger a function when the date of the endDate meet?
I was thinking in moving that decition to the app. That way the app detects when its time to trigger while is using it, but what if the user is not?
How can I trigger the firebase cloud function for emit the invoice independent the interaction of the user with the client app?
I've researched a lot to find an answer but I didn't find anything related so any kind of help is so much appreciated.
*This is the first time Im using FCF.
You can use an onUpdate trigger on documents that may get updated that way. Write code in the function that checks, on every update, if the dates match in the document. If the dates match, emit the invoice, then update the document again with a flag value that indicates the invoice is emitted.
You will also have to use that new flag to determine not to emit the invoice again on further updates (otherwise your function will send an invoice every time it's updated, when the dates match - this boolean will indicate that it already happened).

Resources