我试图弄清楚如何访问args字段的retrieveRowsWithoutLocations。但是,我甚至不确定value参数在UnionType的resolveType函数中会出现什么。
我正在查看文档https://graphql.org/graphql-js/type/#graphqluniontype,但它非常简短,并且没有详细介绍这些信息是从哪里获取的。我试过查看其他来源,但它们不是graphql。
我要做的是访问args.type并检查它的值,然后让联合决定它应该返回哪种类型。
let rows_union =
new graphql.GraphQLUnionType({
name:
"rows_union",
types:
[
many_item,
many_list,
many_display_list,
],
resolveType(value)
{
switch(value)
{
case "item":
return many_item
case "list":
return many_list
case "display_list":
return many_display_list
}
}
})
// Define the Query type
var query =
new graphql.GraphQLObjectType({
name: "Query",
fields:
{
retrieveRowsWithoutLocations:
{
type:
rows_union,
args:
{
_id:
{
type:
nonNullId()
},
page:
{
type:
nonNullInt()
},
page_length:
{
type:
nonNullInt()
},
type:
{
type:
nonNullString()
},
},
async resolve ()
{
}
},
}
})let many_type =
new graphql.GraphQLObjectType({
name: "many_"+name,
fields: {
results: {
type: graphql.GraphQLList(type)
},
total: {
type: graphql.GraphQLNonNull(graphql.GraphQLInt)
},
}
})type是另一个ObjectType
发布于 2019-04-25 10:51:47
您不能直接访问resolveType (或isTypeOf)中的任何解析器参数。当字段被解析时,解析器将返回一些值,或者将解析为该值的承诺。对于返回输出类型、接口或联合的字段,该值应该是JavaScript对象。然后将这个值传递给resolveType,该值用于确定在运行时响应中实际返回的类型。
给出一个类似于
union Animal = Bird | Fish
type Bird {
numberOfWings: Int
}
type Fish {
numberOfFins: Int
}
type Query {
animal: Animal
}您可以想象animal字段的解析器返回像{ numberOfWings: 2 } { numberOfFins: 4 }这样的JavaScript对象。在这里,我们可以使用一个简单的启发式方法来确定类型:
resolveType: (value) => {
if (value.numberOfWings !== undefined) {
return 'Bird'
} else if (value.numberOfFins !== undefined) {
return 'Fish'
}
throw new TypeError(`Unable to resolve type for Animal with value: ${value}`)
}如果我们不返回简单的对象,而是返回特定类的实例,那么我们可以做得更好:
resolveType: (value) => {
if (value instanceof BirdModel) {
return 'Bird'
} else if (value instanceof FishModel) {
return 'Fish'
}
throw new TypeError(`Unable to resolve type for Animal with value: ${value}`)
}不管我们的条件逻辑是什么,只要记住,我们总是只测试解析器返回的值,不管它是什么。
如果不使用类,并且两个或两个以上的类型共享相同的结构,事情就会变得更加棘手。或者,就像在您的情况下,当区分属性(results)是一个数组时,因为检查其中一个元素是禁止的。想象一下我们的联盟是这样的:
union Animal = Cat | Dog
type Cat {
numberOfPaws: Int
}
type Dog {
numberOfPaws: Int
}在这里,不幸的是,我们必须依靠我们的解析器提供一些额外的信息。例如,我们可以返回一些任意字段来标识类型:
// Resolver for animal field
resolve: () => {
return {
numberOfPaws: 4,
kind: 'Dog',
}
}
// Union
resolveType: (value) => {
return value.kind
}但是通过依赖resolveType和isTypeOf的默认实现,我们实际上可以做得更好。
resolve: () => {
return {
numberOfPaws: 4,
__typename: 'Dog',
}
}通过像这样显式地返回__typename,我们实际上可以省略定义的定义。但是,请记住,这再次创建了对解析器的依赖。在可能的情况下,您可能会倾向于使用resolveType和instanceof检查,而不是将resolveType与解析器逻辑分离。
https://stackoverflow.com/questions/55845477
复制相似问题