谁能解释一下如何使用GetItemInput
打电话时输入DocumentClient.get
?
如果我传入任何类型的对象 get
有效,但如果我尝试强烈键入 params 对象,我会收到此错误:
ValidationException: The provided key element does not match the schema
这是我的 lambda 函数代码,其中我将参数作为
any
类型传递:export const get: Handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
console.log(event.pathParameters)
if (!event.pathParameters) {
throw Error("no path params")
}
const params: any = {
Key: {
id: event.pathParameters.id
},
TableName: table
}
console.log(params)
try {
const result: any = await dynamoDb.get(params).promise()
return {
body: JSON.stringify(result.Item),
statusCode: result.$response.httpResponse.statusCode
}
} catch (error) {
console.log(error)
return {
body: JSON.stringify({
message: `Failed to get project with id: ${event.pathParameters!.id}`
}),
statusCode: 500
}
}
}
这是我试图让它与类型
GetItemInput
一起工作的尝试。export const get: Handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
console.log(event.pathParameters)
if (!event.pathParameters) {
throw Error("no path params")
}
const params: GetItemInput = {
Key: {
"id": { S: event.pathParameters.id }
},
TableName: table
}
console.log(params)
try {
const result: any = await dynamoDb.get(params).promise()
return {
body: JSON.stringify(result.Item),
statusCode: result.$response.httpResponse.statusCode
}
} catch (error) {
console.log(error)
return {
body: JSON.stringify({
message: `Failed to get project with id: ${event.pathParameters!.id}`
}),
statusCode: 500
}
}
}
如果我离开
Key
和以前一样阿拉:const params: GetItemInput = {
Key: {
id: event.pathParameters.id
},
TableName: table
}
不出所料,我得到一个类型错误。但无法理解如何形成我的
Key
这样我就没有得到 ValidationException
.注意
id
字段的类型为 String
在 DynamoDB
.
最佳答案
我认为您混合了两个不同的客户端定义文件 DynamoDB
和 DynamoDB.DocumentClient
.当您使用 DynamoDB.DocumentClient
客户端,同时你正在使用接口(interface)DynamoDB.Types.GetItemInput
来自 DynamoDB
.
您应该使用 DynamoDB.DocumentClient.GetItemInput
:
import {DynamoDB} from 'aws-sdk';
const dynamo = new DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
...
const params: DynamoDB.DocumentClient.GetItemInput = {
TableName: table,
Key: {
id: event.pathParameters.id
}
};
const result = await this.dynamo.get(params).promise();
关于amazon-web-services - DynamoDB 获取项目 TypeScript hell ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55167259/