0

I know this has been asked before but I've tried everything from previous posts and still couldn't find a solution for my problem. I can query the table from DynamoDB no problem but can't from lambda. I deleted and created the table with the same name to get rid of a sort key hoping to fix my issue but it did not fix it too. So here is my code

Params

  const queryParams = {
    TableName: tableName,
    KeyConditionExpression: 'postId = :postId',
    ExpressionAttributeValues: { ":postId": postId }
  };

Schema

   type LikeRelationship
      @model(
        mutations: {
          create: "createLikeRelationship"
          delete: "deleteLikeRelationship"
          update: null
        }
        timestamps: null
      )
      @auth(
        rules: [
          {
            allow: owner
            ownerField: "likerId"
            operations: [read, create, delete]
          }
          { allow: public, provider: iam, operations: [read] }
        ]
      )
      @key(fields: ["postId"]) {
      postId: ID!
      postOwnerId: String!
      likerType: String
      likerName: String
      likerId: ID!
      timestamp: Int!
    }

Full Lambda Code

/* Amplify Params - DO NOT EDIT
    API_GROOVESECONDED_GRAPHQLAPIIDOUTPUT
    API_GROOVESECONDED_LIKERELATIONSHIPTABLE_ARN
    API_GROOVESECONDED_LIKERELATIONSHIPTABLE_NAME
    ENV
    REGION
Amplify Params - DO NOT EDIT */

exports.handler = async (event, context, callback) => {
  
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10' });

const tableName = 'LikeRelationship-76mphdcsf5cijbgq5kkcny3xpe-staging';
async function deleteItems(tableName, postId ) {

  const queryParams = {
    TableName: tableName,
    KeyConditionExpression: 'postId = :postId',
    ExpressionAttributeValues: { ":postId": postId }
  };
  
  const queryResults = await docClient.query(queryParams).promise();

  if (queryResults.Items && queryResults.Items.length > 0) {
    
    const batchCalls = chunks(queryResults.Items, 25).map( async (chunk) => {
      const deleteRequests = chunk.map( item => {
        return {
          DeleteRequest : {
            Key : {
              'partitionId' : item.partitionId,
              'sortId' : item.sortId,

            }
          }
        };
      }
      );


      const batchWriteParams = {
        RequestItems : {
          [tableName] : deleteRequests
        }
      };

await docClient.batchWrite(batchWriteParams).promise();

    });

await Promise.all(batchCalls);


    
  }
}
    
    if (event.body !== null && event.body !== undefined) {
        let data = JSON.parse(event.body);

        if (typeof data.postId === 'undefined') {
            return sendRes(404, '{ error: true, message: "postId undefined." }');
        }
        try {
         await deleteItems(tableName, data.postId );
        } catch (e) {
           return sendRes(404, '{ error: true, message: " ' + e + data.postId + typeof data.postId + ' " }');
        }
         
        return sendRes(200, '{ "error": false, "message": "Success" }');
    }    
    
    return sendRes(404, '{ error: true, message: "Event body null or undefined." }');
};
const sendRes = (status, body) => {
    var response = {
        statusCode: status,
        headers: {
            "Content-Type" : "application/json",
            "Access-Control-Allow-Headers" : "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
            "Access-Control-Allow-Methods" : "OPTIONS,POST",
            "Access-Control-Allow-Credentials" : true,
            "Access-Control-Allow-Origin" : "*",
            "X-Requested-With" : "*"
        },
        body: body
    };
    return response;
};


// https://stackoverflow.com/a/37826698/3221253
function chunks(inputArray, perChunk) {
  return inputArray.reduce((all,one,i) => {
    const ch = Math.floor(i/perChunk); 
    all[ch] = [].concat((all[ch]||[]),one); 
    return all;
 }, []);
}

IAM Role

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "dynamodb:BatchGetItem",
                "dynamodb:BatchWriteItem",
                "dynamodb:Delete*",
                "dynamodb:Get*",
                "dynamodb:Scan",
                "dynamodb:Query"
            ],
            "Resource": [
                "arn:aws:dynamodb:eu-central-1:382762466424:table/LikeRelationship-76mphdcsf5cijbgq5kkcny3xpe-staging",
                "arn:aws:dynamodb:eu-central-1:382762466424:table/LikeRelationship-76mphdcsf5cijbgq5kkcny3xpe-staging/index/*"
            ]
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "dynamodb:List*",
                "dynamodb:Describe*"
            ],
            "Resource": [
                "arn:aws:dynamodb:eu-central-1:382762466424:table/LikeRelationship-76mphdcsf5cijbgq5kkcny3xpe-staging",
                "arn:aws:dynamodb:eu-central-1:382762466424:table/LikeRelationship-76mphdcsf5cijbgq5kkcny3xpe-staging/index/*"
            ]
        }
    ]
}
qublaidev
  • 69
  • 4

0 Answers0