GraphQLServer 联合类型 "Abstract type N must resolve to an Object type at runtime" 错误



给定GraphQLunion返回类型:

union GetBankAccountsResponseOrUserInputRequest = GetAccountsResponse | UserInputRequest

意味着由给定的解析器返回:

type Query {
getBankAccounts: GetBankAccountsResponseOrUserInputRequest!
}

我收到了关于__resolveType__isTypeOf函数的以下警告或错误:

Abstract type N must resolve to an Object type at runtime for field Query.getBankAccounts with value { ..., __isTypeOf: [function __isTypeOf] }, received "undefined". Either the N type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.'

我已经在github问题和SO问题中搜索了好几天,希望解决这个错误。

在我的解析器中实现__resolveType__isTypeOf不起作用:

export const Query = {
getBankAccounts: (parent, args, context: IContext, info) => {
return {
__isTypeOf(obj) { // OR __resolveType, none of them work
return `GetAccountsResponse`;
},
accounts: []
};
},
};

由于在我的解析器中实现__resolveType__isTypeOf对我不起作用,我最终通过将__typename直接添加到解析器返回对象中来解决这个问题。

getBankAccounts解析器实现中:

async getBankAccounts(): GetBankAccountsResponseOrUserInputRequest {
if (shouldGetUserInputRequest()) {
return {
__typename: "UserInputRequest",
...response,
};
}
return {
__typename: "GetAccountsResponse",
accounts,
};
}

希望这能帮助到别人。

解析程序映射设置不正确。

传递给ApolloServer(或makeExecutableSchema(的解析程序映射应该是一个对象,其键是架构中的类型名,每个键映射到另一个对象的键是该类型上的字段名。然后,每个字段名称都映射到一个解析程序函数。

const resolvers = {
SomeType: {
someField: (parent, args, context, info) => { ... },
},
}

您可以使用相同的解析程序映射来传递联合或接口的resolveType函数。模式是相同的,但类型的名称是联合或接口的名称,而不是字段名称,密钥是__resolveType:

const resolvers = {
SomeType: {
someField: (parent, args, context, info) => { ... },
},
SomeUnion: {
__resolveType: (parent) => { ... },
}
}

resolveType函数应该始终返回一个字符串,该字符串与架构中现有对象类型的名称相匹配。

如果使用__isTypeOf而不是__resolveType,那么这看起来会有点不同,因为isTypeOf函数与特定的对象类型相关,而不是与接口或并集相关。这些都显示在文档中。所以解析器映射看起来像这样:

const resolvers = {
SomeType: {
someField: (parent, args, context, info) => { ... },
__isTypeOf: (parent) => { ... },
},
}

__isTypeOf应该始终返回truefalse,这取决于传入的对象实际上是否为该类型。

您只需要使用__resolveType__isTypeOf。如果使用__isTypeOf,则必须将其添加到联合或接口中的所有可能的对象类型中。

相关内容

最新更新