- Newest
- Most votes
- Most comments
According to your question,
You have a DynamoDB Table which has a partition key userId and sort key createdAt. These attributes will be combined as Primary Key. I created an example table posts with the following items
You are saying that you want to fetch posts within 1 day and if they are less than 20, you need to fetch posts within 2 days. This is not a good practice. I think what you want is to fetch 20 latest posts of a user.
This is the lambda code that fetches last 20 items(posts) of a user.
Note:- runtime: nodejs 18x, Used AWS SDK for JavaScript v3
import { DynamoDBClient, QueryCommand, ScanCommand } from "@aws-sdk/client-dynamodb";
export const ddbClient = new DynamoDBClient();
export const handler = async(event) => {
const endDate = '2023-01-07T17:18:44.219Z';
const params = {
TableName: 'posts',
KeyConditionExpression: 'userId = :userId AND createdAt <= :endDate',
ExpressionAttributeValues: {
':endDate': {S: endDate},
':userId': {S: '1'}
},
Limit:20,
ScanIndexForward: false,
};
const result = await ddbClient.send(new QueryCommand(params));
console.log(result.Items);
const response = {
statusCode: 200,
body: JSON.stringify(result.Items),
};
return response;
};
Here, I have hardcoded the userId and endDate. You can pass it through event object. Limit: 20 means it give only 20 Items and ScanIndexForward: false gives the items in descending order
Hope this answer helps
Relevant content
- asked 3 years ago
- asked a year ago
- asked 3 years ago
- AWS OFFICIALUpdated 3 years ago
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated a year ago
- AWS OFFICIALUpdated 3 years ago
If this returns post less than 20 then what to do? your end date is const endDate = '2023-01-07T17:18:44.219Z'; , i need to fetch again 1 day minus form the date you added
The
createdAt <= :endDate
means that you want everything less than that specific date. It starts with the most recent date from that date and goes to least recent due theScanIndexForward: false
. You also can omit thecreatedAt <= :endDate
if the :endDate is the time of the query.