【问题标题】:defining optional attribute in AWS Api Gateway -> DynamoDB mapping在 AWS Api Gateway -> DynamoDB 映射中定义可选属性
【发布时间】:2016-07-04 16:32:10
【问题描述】:

我正在关注:Using Amazon API Gateway as a proxy for DynamoDB

以博客的示例为例,我想加强 Api Gateway 将数据写入 dynamodb 表前端的内容和方式。为此我在 Api Gateway 中定义了如下映射:

{ 
    "TableName": "Comments",
    "Item": {
      "commentId": {
        "S": "$context.requestId"
       },
       "pageId": {
         "S": "$input.path('$.pageId')"
       },
       "userName": {
         "S": "$input.path('$.userName')"
       },
       "message": {
         "S": "$input.path('$.message')"
       }
    }
}

接下来,使用以下示例进行测试就可以了:

{
  "pageId": "breaking-news-story-01-18-2016",
  "userName": "Just Saying Thank You",
  "message": "I really enjoyed this story!!"
}

但是,假设我想保持与上面相同的映射,但想让message 成为可选的。我该怎么做?我无法让它工作。我试过了:

  1. 按原样使用上述映射,但发送没有message-attribute 的正文。 --> “一个或多个参数值无效:AttributeValue 可能不包含空字符串” 2 按原样使用上述映射,但发送带有message=null 的正文。 --> "一个或多个参数值无效:AttributeValue 不能包含空字符串"
  2. 通过省略mapping 的定义来更改上面的映射-> 现在传递一个没有message 的主体显然成功了。但是,发送带有message 的正文不会通过message(这是我的预期,但想用尽所有选项)
  3. 根本不使用映射。显然这是可行的,但现在所有内容都是未经过滤的,这是不需要的。

显然我可以使用 AWS lambda 来进行映射,但这感觉像是一个常见的用例,即:可选属性,这必须可以直接在 Api Gateway 中实现。

【问题讨论】:

    标签: amazon-web-services amazon-dynamodb aws-api-gateway


    【解决方案1】:

    感谢@ka:

    解释:APi 网关自动填充不存在的属性与空字符串或其他东西。这需要从 if 中排除。

    还要注意 if 语句后面的关键 ,

    { 
        "TableName": "Comments",
        "Item": {
          "commentId": {
            "S": "$context.requestId"
           },
           "pageId": {
             "S": "$input.path('$.pageId')"
           },
           "userName": {
             "S": "$input.path('$.userName')"
           }#if($input.path('$.description') && $input.path('$.message') != ""),
           "message": {
             "S": "$input.path('$.message')"
           }
           #end
        }
    }
    

    【讨论】:

      【解决方案2】:

      您介意试试这个映射模板吗?如果消息为NULL,则不会添加到正文中。

      { 
          "TableName": "Comments",
          "Item": {
            "commentId": {
              "S": "$context.requestId"
             },
             "pageId": {
               "S": "$input.path('$.pageId')"
             },
             "userName": {
               "S": "$input.path('$.userName')"
             }#if ($.message),
             "message": {
               "S": "$input.path('$.message')"
             }
             #end
          }
      }
      

      谢谢, -嘉侯

      【讨论】:

      • 很遗憾这不起作用:Execution failed due to configuration error: Unable to transform request
      • 让它工作。感谢您为我指明正确的方向。看我的回答
      猜你喜欢
      • 2021-12-30
      • 2020-09-28
      • 1970-01-01
      • 2017-11-30
      • 2019-11-07
      • 2021-04-13
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多