Reputation: 1093
So i wanted to give AWS Amplify a try, as the new project I am starting will start our simple but will grow to be more complex and I dont want to go the Firebase route for that reason. So I setup Auth and created my Data Models and added the Amplify Lib to my angular front end. I can login and read my data. So far so good.
Now I wanted to do a basic query on my data. Filtering based on a basic string field is easy for things like the Name:
const members = await DataStore.query(Member, m => m.firstName("eq", "Steve"));
What I can't seem to find is any documentation on how you would query things like dates?
I have a model called Event, and there is how you'd do a typical create for an event (note the fields StartTimestamp
, and EndTimestamp
):
await DataStore.save(
new Event({
"Title": "Lorem ipsum dolor sit amet",
"StartTimestamp": "1970-01-01T12:30:23.999ZM",
"EndTimestamp": "1970-01-01T12:30:23.999ZM",
"Notes": "Lorem ipsum dolor sit amet"
})
);
Both StartTimestamp
, and EndTimestamp
are of type AWSDateTime
:
When pulling the data for events I see the type in JS as I read them is string. So how do I query the dates then? string comparison wont help. I know the underlying DB for AWS Amplify is GraphQL and querying a date there is easy but I am still limited to what the Amplify DataStore Lib gives me to work with.
Any advice would be greatly appreciated.
Upvotes: 1
Views: 2387
Reputation: 323
I just want to add some additional information about AWS and date fields.
More info in AWS types reference
Both have their uses.
As stated above, just convert your variable date value to a ISO 8601 formatted string representation.
Upvotes: 1
Reputation: 428
AWS Amplify leverages AWS AppSync to manage the underlying GraphQL. A model can indeed be setup in the AWS Admin UI with a field of type AWSDateTime. In the local amplify installation folder the model schema shows the field as string. AppSync indeed confirms that AWSDateTime is an extended ISO 8601 date and time string.
The AWS Amplify Datastore documentation only make mentions of predicates to filter queries for strings, numbers and lists not dates. This means you cannot query against actual date values as below (in Angular)
const members = await DataStore.query(Member, m => m.StartTimeStamp("lt", new Date()));
However you can leverage the idea that ISO 8601 date strings are implicitly lexicographically ordered to compare the dates. You can then query by first changing the date you wish to compare to into a string in the appropriate ISO 8601 format then doing a string comparison. The previous search then becomes (in Angular)
const currentDate = this.datePipe.transform(new Date(), 'YYYY-MM-ddThh:mm:ss.SSS\'Z\'');
const members = await DataStore.query(Member, m => m.StartTimeStamp("lt", currentDate));
By converting the date to compare with to a string you can therefore use the string predicates to filter against AWSDateTime fields in queries.
Upvotes: 0