在 aws-sdk v3 中执行 DynamoDB get 时,出现“ValidationException:提供的关键元素与架构不匹配”

问题描述 投票:0回答:1

我按照文档创建了获取流程。

import { DynamoDBClient, PutItemCommand } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, GetCommand } from '@aws-sdk/lib-dynamodb';
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';
export class DynamoDb {
    private readonly tableName: string;
    public readonly client: DynamoDBClient;

    constructor(tableName = '') {
        this.client = new DynamoDBClient({
            region: 'ap-northeast-1',
        });
        this.tableName = tableName ? tableName : '';
    }

    public async get(keyName: string, key: string | number) {
        try {
            const params = {
                TableName: this.tableName,
                Key: marshall({ [keyName]: key,
                "sort_key": "1-1","cp_id": 1 }),
            };
            console.log(params)
            const command = new GetCommand(params);
            const documentClient = DynamoDBDocumentClient.from(this.client)
            const result = await documentClient.send(command);
            return { body: JSON.stringify(unmarshall(result.Item || {})) };
        } catch (err: unknown) {
            throw err;
        }
    }
}

然后,当我在测试代码中运行该流程时,出现错误。\

import { describe, expect, it } from '@jest/globals';
import { DynamoDb } from '../../myDynamodb';

describe('Unit test for DynamoDb', function () {
    it('verifies successful response', async () => {
        const dynamoDb = new DynamoDb("test-db");
        const result = await dynamoDb.get('test_id', 1);
        expect(result).toEqual(1);
    });
});
● Unit test for DynamoDb › verifies successful response
 ValidationException: The provided key element does not match the schema

      27 |             const command = new GetCommand(params);
      28 |             const documentClient = DynamoDBDocumentClient.from(this.client)
    > 29 |             const result = await documentClient.send(command);
         |                            ^
      30 |             return { body: JSON.stringify(unmarshall(result.Item || {})) };
      31 |         } catch (err: unknown) {
      32 |             throw err;

      at throwDefaultError (node_modules/@smithy/smithy-client/dist-cjs/default-error-handler.js:eight:22)
      at node_modules/@smithy/smithy-client/dist-cjs/default-error-handler.js:18:39
      at de_GetItemCommandError (node_modules/@aws-sdk/client-dynamodb/dist-cjs/protocols/Aws_json1_0.js:1554:20)
      at node_modules/@smithy/middleware-serde/dist-cjs/deserializerMiddleware.js:seven:24
      at node_modules/@aws-sdk/lib-dynamodb/dist-cjs/baseCommand/DynamoDBDocumentClientCommand.js:26:34
      at node_modules/@aws-sdk/middleware-signing/dist-cjs/awsAuthMiddleware.js:14:20
      at node_modules/@smithy/middleware-retry/dist-cjs/retryMiddleware.js:27:46
      at node_modules/@aws-sdk/middleware-logger/dist-cjs/loggerMiddleware.js:seven:26
      at DynamoDb.get (cf/.aws-sam/build/DynamoDbLayer/nodejs/src/index.ts:29:28)
      at Object.<anonymous> (cf/.aws-sam/build/DynamoDbLayer/nodejs/tests/unit/get.test.ts:seven:24)

我知道错误是架构定义不正确。

这是 DynamoDB 的架构。

Partition Key: target(S)
sort key: sort_key(S)
test_id(N)

我的猜测是,DynamoDB 架构和您尝试传递的实际参数都很好。 我是否必须包含分区键,或者是否有其他方法来指定它?

node.js amazon-web-services amazon-dynamodb aws-sdk
1个回答
0
投票

您使用

DocumentClient
,因此无需
marshall
,因为请求需要 JSON 格式。

我也不确定

cp_id
是什么,但它不应该包含在密钥中。仅应包含分区键
target
和排序键
sort_key
,因为它们应唯一标识该项目。

const params = {
                TableName: this.tableName,
                Key: { 
                 [keyName]: key,
                 "sort_key": "1-1" 
               },
            };
© www.soinside.com 2019 - 2024. All rights reserved.