Input List of Data into DynamoDB

0

I'm calling my Lambda from an API Gateway and as Input give it a userID and a MMMY, which is just Month and year. Besides that I input data in the form of a List of Objects that look like this:

{
  "data": [
    {
      "dt": 3,
      "bl": 0,
      "bs": "Einnahme Fahrten",
      "ss": 7
    },
    {
      "dt": 28,
      "bl": 0,
      "bs": "Einnahme Fahrten",
      "ss": 7
    },//can grow a lot more
  ]
}

How can I adjust my code that is just inputting the first item of the List, to store the whole list:

switch (event.routeKey) {
      case "PUT /sheets/{userID}/{MMYY}":
        console.log(
          "MYY",
          event.pathParameters.MMYY,
          "userID",
          event.pathParameters.userID,
          "Json",
          JSON.parse(event.body)
        );
        // Assuming the request body is in the form { "data": [...] }
        const data = event.body ? JSON.parse(event.body).data : [];
        const MMYY = parseInt(event.pathParameters.MMYY);
        // Create an array of PutCommand operations
        const putCommands = data.map((item) => {
          return new PutCommand({
            TableName: tableName,
            Item: {
              userID: event.pathParameters.userID,
              MMYY: MMYY,
              dt: item.dt,
              bl: item.bl,
              bs: item.bs,
              ss: item.ss,
            },
          });
        });

        // Execute all PutCommand operations
        await Promise.all(putCommands.map((command) => dynamo.send(command)));
1 Answer
1

You don't need to loop the PutItem. You also only need the first item in data list:

switch (event.routeKey) {
          case "PUT /sheets/{userID}/{MMYY}":
            const MMYY = parseInt(event.pathParameters.MMYY);
    
            // Assuming the request body is in the form { "data": [...] }
            const data = event.body ? JSON.parse(event.body).data : [];
    
            // Create an array of PutCommand operations
              new PutCommand({
                TableName: tableName,
                Item: {
                  userID: event.pathParameters.userID,
                  MMYY: MMYY,
                  data: data
                },
              })
    
            // Execute all PutCommand operations
            await dynamo.send(command);
profile pictureAWS
EXPERT
answered 6 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions