最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

使用lamda无法正常工作在Dynamodb中保存字符串数据

网站源码admin20浏览0评论

使用lamda无法正常工作在Dynamodb中保存字符串数据

使用lamda无法正常工作在Dynamodb中保存字符串数据

我很简单地创建一个后置api,在其中将数据发送到DynamoDb,我使用硬编码数据,但是不知道为什么当我尝试添加事件值时它不起作用。

我的lambda函数

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'us-east-2', apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {
    const params = {
        Item: {
            "QuestionID": {
                S: context.awsRequestId
            },
            "Would": {
                S: event.would
            },
            "Rather": {
                S: event.rather
            },
            "wouldClick": {
                N: event.wouldClick
            },
            "ratherClick": {
                N: event.ratherClick
            }
        },
        TableName: "Would-You-Rather"
    };
    dynamodb.putItem(params, function(err, data) {
        if (err) {
            console.log(err);
            callback(err);
        } else {
            console.log(data);

            callback(null, data);
        }
    });
};

这是我在发布方法中使用的模型

{
  "$schema": "",
  "title": "WouldYouRatherModel",
  "type": "object",
  "properties": {
    "would": {"type": "string"},
    "rather": {"type": "string"},
    "wouldClick": {"type": "integer"},
    "ratherClick": {"type": "integer"}
  },
  "required": ["would", "rather", "wouldClick", "ratherClick"]
}

我的集成请求映射

#set($inputRoot = $input.path('$'))
{
    "would" : "$inputRoot.would",
    "rather" : "$inputRoot.rather",
    "wouldClick" : "$inputRoot.wouldClick",
    "ratherClick" : "$inputRoot.ratherClick"
}

如果我在lamda函数中对值进行硬编码并在lamda中测试其将值保存在数据库中,这就是我对值进行硬编码的方式

   "QuestionID": {
        S: context.awsRequestId
    },
    "Would": {
        S: "helllo"
    },
    "Rather": {
        S: "bye"
    },
    "wouldClick": {
        N: 1
    },
    "ratherClick": {
        N: 2
    }

但是问题是,当我在lambda函数中添加事件值并尝试从资源中测试发布API时,它显示此错误

"errorMessage": "There were 2 validation errors:\n* InvalidParameterType: Expected params.Item['wouldClick'].N to be a string\n* InvalidParameterType: Expected params.Item['ratherClick'].N to be a string"

我认为问题在于我以错误的方式传递了字符串值?因为如果lamda或模块有问题,那么硬编码的值也将不会保存在DynamoDB中,这会在我发送值时引起错误。

回答如下:

即使wouldClickratherClick是数字类型(N),也需要将它们作为字符串传递给DynamoDB。这就是错误消息告诉您的内容。

The documentation on DynamoDB attribute values说:

数字作为字符串通过网络发送到DynamoDB,以最大程度地跨语言和库实现兼容性。但是,DynamoDB将它们视为数学运算的数字类型属性。

Number变量的格式应如下:

"wouldClick": { "N": "1" },
"ratherClick": { "N": "2" }
发布评论

评论列表(0)

  1. 暂无评论