首页 > 解决方案 > AWS AppSync GraphQL 输入验证 - 忽略额外字段?

问题描述

我的模式中有一个input类型,它指定了许多属性,正如它打算做的那样。问题是我要发送到持久化这些对象的突变是一个具有可能更改的任意字段的对象。就目前而言,如果我发送架构中未指定的属性,则会收到错误消息:

Validation error of type WrongType: argument 'input' with value (...)
   contains a field not in 'BotInput': 'ext_gps' @ 'setBot'

具体来说,我的input类型没有指定属性exp_gps,并且提供了该字段。

我的问题

有没有办法让输入验证简单地忽略架构中没有的任何属性,以便它继续执行仅使用架构中指定的任何内容的突变?通常我不想保留额外的属性,所以只要添加其他属性就可以删除它们。

标签: graphqlaws-appsync

解决方案


GraphQL 不支持任意字段,有一个支持类型的RFC,Map但尚未合并/批准到规范中。

我看到两种可能的解决方法都需要稍微更改您的架构。

假设您有以下架构:

type Mutation {
 saveBot(input: BotInput) : Boolean
}

input BotInput {
 id: ID!
 title: String
}

输入对象是:

{
 "id": "123",
 "title": "GoogleBot",
 "unrelated": "field",
 "ext_gps": "else"
}

选项 1:将任意字段传递为AWSJSON

您可以将架构更改为:

type Mutation {
 saveBot(input: BotInput) : Boolean
}

input BotInput {
 id: ID!
 title: String
 arbitraryFields: AWSJSON  // this will contain all the arbitrary fields in a json string, provided your clients can pluck them from the original object, make a map out of them and json serialize it. 
}

因此,我们示例中的输入现在是:

{
 "id": "123",
 "title": "GoogleBot",
 "arbitraryFields": "{\"unrelated\": \"field\", \"ext_gps\": \"else\"}"
}

在您的解析器中,您可以获取arbitraryFields字符串,对其进行反序列化,并在将BotInput对象传递给数据源之前对对象上的值进行水合。

选项 2:将输入传递为AWSJSON

原理是一样的,但你传递整个BotInputas AWSJSON

type Mutation {
 saveBot(input: AWSJSON) : Boolean
}

您不必进行解析器水合,也不必更改您的客户端,但您会丢失 GraphQL 类型验证,因为BotInput现在整体是一个 blob。


推荐阅读