NodeJS ValidationException:提供的关键元素与架构不匹配

发布于 2025-01-09 04:31:34 字数 5112 浏览 1 评论 0原文

我知道以前有人问过这个问题,但我已经尝试了以前帖子中的所有内容,但仍然找不到解决我的问题的方法。我可以从 DynamoDB 查询表没有问题,但不能从 lambda 查询。我删除并创建了具有相同名称的表以摆脱排序键,希望解决我的问题,但它也没有解决它。这是我的代码

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/*"
            ]
        }
    ]
}

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/*"
            ]
        }
    ]
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文