AWS无服务器dynamodb-删除项目无效

时间:2020-10-12 10:01:22

标签: amazon-web-services aws-lambda amazon-dynamodb serverless-framework

我已将无服务器应用程序部署到具有无服务器框架的AWS。我有一个简单的待办事项应用程序。

TodoItem看起来像这样:

export interface TodoItem {
  userId: string
  todoId: string
  createdAt: string
  name: string
  dueDate: string
  done: boolean
  attachmentUrl?: string
}

这是我设置动力发电机的方式:

TodosDynamoDBTable:
      Type: 'AWS::DynamoDB::Table'
      Properties:
        AttributeDefinitions:
          - AttributeName: userId
            AttributeType: S
          - AttributeName: todoId
            AttributeType: S
          - AttributeName: createdAt
            AttributeType: S
        KeySchema:
          - AttributeName: todoId
            KeyType: HASH
          - AttributeName: createdAt
            KeyType: RANGE
        BillingMode: PAY_PER_REQUEST
        TableName: ${self:provider.environment.TODOS_TABLE}
        GlobalSecondaryIndexes:
          - IndexName: ${self:provider.environment.USER_ID_INDEX}
            KeySchema:
              - AttributeName: userId
                KeyType: HASH
              - AttributeName: createdAt
                KeyType: RANGE
            Projection:
              ProjectionType: ALL

我的删除todo lambda函数如下所示:

export const handler: APIGatewayProxyHandler = async (
  event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> => {
  const todoId = event.pathParameters.todoId

  logger.info('Event: ', event)
  logger.info('Deleting a todo with id: ', todoId)
  // TODO: Remove a TODO item by id
  await deleteTodo(todoId, getUserId(event))

  return {
    statusCode: 204,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true
    },
    body: null
  }
}

我正在删除这样的项目:

async deleteTodo(todoId: string, userId: string): Promise<any> {
    await this.docClient
      .delete({
        TableName: this.todosTable,
        Key: {
          userId,
          todoId
        }
      })
      .promise()
  }

但是,当我尝试删除某个项目时,我得到了:

502错误的网关

在cloudwatch日志中,我可以看到出现此错误:

2020-10-12T08:43:45.648Z 7ff99035-bf3d-4158-b311-1e6d7e73a6e5错误 调用错误{“ errorType”:“ ValidationException”,“ errorMessage”:“ The 提供的关键元素与 schema“,” code“:” ValidationException“,” message“:”提供的密钥 元素与 schema“,” time“:” 2020-10-12T08:43:45.629Z“,” requestId“:” SRSL15PC9C3BN4RC4F5K3ERFNNVV4KQNSO5AEMVJF66Q9ASUAAJG“,” statusCode“:400,” retryable“:false,” retryDelay“:”,49.16692 [“ ValidationException: 提供的键元素与架构“,”不符 构造函数.httpResponse (/var/task/src/lambda/http/webpack:/node_modules/aws-sdk/lib/protocol/json.js:47:1)“,” 在builder.shift上[作为callListeners] (/var/task/src/lambda/http/webpack:/node_modules/aws-sdk/lib/sequential_executor.js:100:1)“,” 在builder.doneCallback [发出] (/var/task/src/lambda/http/webpack:/node_modules/aws-sdk/lib/sequential_executor.js:75:1)“,” 在Constructor.call上[作为emitEvent] (/var/task/src/lambda/http/webpack:/node_modules/aws-sdk/lib/request.js:683:1)“,” 在builder.emit (/var/task/src/lambda/http/webpack:/node_modules/aws-sdk/lib/request.js:22:1)“,” 在r.call [作为runTo] (/var/task/src/lambda/http/webpack:/node_modules/aws-sdk/lib/state_machine.js:14:1)“,” 在runTo (/var/task/src/lambda/http/webpack:/node_modules/aws-sdk/lib/state_machine.js:26:1)“,” 在builder.done (/var/task/src/lambda/http/webpack:/node_modules/aws-sdk/lib/request.js:38:1)“,” 在构造函数 (/var/task/src/lambda/http/webpack:/node_modules/aws-sdk/lib/request.js:685:1)“,” 在构造函数上。错误[作为callListeners] (/var/task/src/lambda/http/webpack:/node_modules/aws-sdk/lib/sequential_executor.js:108:1)“]}

我怀疑我为dynamodb表设置了错误的哈希和范围键。我不确定为这样的表进行设置的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

在表定义中,键由todoIdcreatedAt组成。但是,您的删除功能使用todoIduserId作为键。这不起作用。

我不确定在拥有已经假定为唯一的待办事项ID的情况下为什么需要用户ID。如果您只是这样从删除参数对象的userId属性中删除Key,是否可以正常工作?

async deleteTodo(todoId: string, userId: string): Promise<any> {
    await this.docClient
      .delete({
        TableName: this.todosTable,
        Key: {
          todoId
        }
      })
      .promise()
  }
相关问题