返回也具有字段解析器的 Appsync GraphQL 类型

Returning Appsync GraphQL type that also has field resolvers

我想 return 来自 AddImageSet 突变的 ImageSet 类型。但我似乎无法做到这一点,因为我的 ImageSet 类型上的每个字段都有自己的解析器,它正在覆盖解析器映射模板。

架构:

type ImageSet {
    SetKey: ID
    SetName: String
    SetCreatedAt: AWSTimestamp
    SetDescription: String
    SetTags: [Tag]
}

type Mutation {
    AddImageSet(setName: String!, setDescription: String): ImageSet
}

这里是突变:

{
    "version" : "2017-02-28",
    "operation" : "PutItem",
    "key" : {
        "PartitionKey" : { "S" : "ImageSet" },
        "SortKey" : { "S" : "ImageSet-$util.autoId()" }
    },
    "attributeValues" : {
        "Name": { "S" : "${context.arguments.setName}" },
        "Description": { "S" : "${context.arguments.setDescription}" },
        "CreatedAt": { "N" : $util.time.nowEpochSeconds() },
    }
}

和响应映射模板

{
    "SetKey" : "$context.result.SortKey",
    "SetName" : "$context.result.Name",
    "SetCreatedAt" : $context.result.CreatedAt,
    "SetDescription" : "$context.result.Description"
}

当我 运行 这样做时,由 AddImageSet 突变 return 编辑的对象的每个字段都设置为空,因为字段解析器正在覆盖 AddImageSet 突变的响应映射模板。

我已经通过创建一个重复的 'ImageSetResult' 类型解决了这个问题,只是没有附加到该字段的解析器。然后,如果 AddImageSet Mutation return 是这样,一切都很好。但这些似乎有些多余。

有更好的方法吗?

这是 GraphQL 中的预期行为。如果您在 ImageSet.SetKey 上有解析器并且您的 Mutation.AddImageSet 突变 returns 类型为 ImageSet,将调用选择集中列出的每个字段的解析器。 Mutation.AddImageSet 返回的值将被子解析器返回的任何值覆盖。

要添加更多上下文,您从 Mutation.AddImageSet 响应映射模板返回的值将是 $[=47 的值=] 当您在 ImageSet.SetKey/SetName/SetCreatedAt 解析器中时。从这些解析器中,您可以执行如下操作:

#if( $ctx.source.SetKey ) "$ctx.source.SetKey" #else .. whatever SetKey does .. #end

在 SetKey/SetName/etc 上需要解析器是有原因的吗?如果对象已经由 Mutation.AddImageSetQuery.AddImageSet 等返回,那么您不需要该类型的解析器。

另一个注意事项。您想要名称 ImageSet.SetName 而不仅仅是 ImageSet.Name 是有原因的吗?这就是您将其存储在 DynamoDB 中的方式?这似乎增加了很多您可以避免的复杂性。