在您当前的映射模板中,您将类别存储为 DDB 中的“S”,这意味着字符串,这就是您获得 DynamoDB 列表的字符串化版本的原因。假设您正在运行一个看起来像这样的突变:
mutation {
create(input: { title: "Test 1", categories: [{ name: "category 1" }] }) {
title
categories {
name
}
}
}
然后您应该将映射模板更改为:
{
"version": "2017-02-28",
"operation": "PutItem",
"key": {
"userId": {
"S": "$context.identity.username"
}
},
"attributeValues": $util.toJson($ctx.args)
}
如果您想将数据存储为 DynamoDB 列表和地图,则可以使用上述模板。如果您尝试将 JSON 作为 JSON 字符串化 blob 存储在 DynamoDB“S”属性中但没有 L 和 M,则改为将模板更改为:
{
"version": "2017-02-28",
"operation": "PutItem",
"key": {
"userId": {
"S": "$context.identity.username"
}
},
#set( $attrs = $util.dynamodb.toMapValues($ctx.args))
## NOTE: The $util.toJson instead of the dynamodb version which adds L, M, S, etc
#set( $attrs.categories = { "S": "$util.toJson($ctx.args.categories)"})
"attributeValues": $util.toJson($attrs)
}
然后在响应映射模板中,您需要将 JSON 解析为返回的结构化 JSON,而不是 JSON 字符串化字符串。
## Get the result and parse categories into structured objects.
#set( $result = $ctx.result)
#set( $result.categories = $util.parseJson($ctx.result.categories))
## Return the full JSON payload
$util.toJson($result)
编辑(更多细节):
我有这些架构部分(注意这不完整):
type Category {
name: String
}
input CategoryInput {
name: String
}
input CreatePostInput {
title: String
categories: [CategoryInput]
}
type Post {
id: ID!
title: String
categories: [Category]
}
type Mutation {
createPost(input: CreatePostInput!): Post
}
而这个请求映射模板正是:
## Mutation.createPost request mapping template
#set( $attrs = $util.dynamodb.toMapValues($ctx.args.input))
#set( $attrs.categories = { "S": "$util.toJson($ctx.args.input.categories)"})
{
"version": "2017-02-28",
"operation": "PutItem",
"key": {
"id": $util.dynamodb.toDynamoDBJson($util.autoId()),
},
"attributeValues": $util.toJson($attrs),
"condition": {
"expression": "attribute_not_exists(#id)",
"expressionNames": {
"#id": "id",
},
},
}
而这个响应映射模板
## Mutation.createPost response mapping template
## Get the result and parse categories into structured objects.
#set( $result = $ctx.result)
#set( $result.categories = $util.parseJson($ctx.result.categories))
## Return the full JSON payload
$util.toJson($result)
然后我能够运行这个查询:
mutation {
createPost(input: {
title: "Hello, world!",
categories: [
{
name: "cat1"
}
]
}) {
id
title
categories {
name
}
}
}
并得到了这样的回应:
{
"data": {
"createJSONTest2": {
"id": "c72ff226-0d67-41c4-9c47-784955a64bc5",
"title": "Hello, world!",
"categories": [
{
"name": "cat1"
}
]
}
}
}
当我进入 DynamoDB 控制台时,它被存储为类别属性
[{"name":"cat1"}]
看来这一切正常。Lmk 如果您需要进一步的帮助调试。