GraphQLServer 联合类型“抽象类型 N 必须在运行时解析为对象类型”错误

Gus*_*Gus 3 typescript graphql

给定 GraphQLunion返回类型:

union GetBankAccountsResponseOrUserInputRequest = GetAccountsResponse | UserInputRequest
Run Code Online (Sandbox Code Playgroud)

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

type Query {
  getBankAccounts: GetBankAccountsResponseOrUserInputRequest!
}
Run Code Online (Sandbox Code Playgroud)

我收到有关 a__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.'
Run Code Online (Sandbox Code Playgroud)

我在 github issues 和 SO questions 中搜索了几天,希望解决这个错误。

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

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

Gus*_*Gus 6

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

getBankAccounts解析器实现中:

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

    return {
      __typename: "GetAccountsResponse",
      accounts,
    };
  }
Run Code Online (Sandbox Code Playgroud)

希望这对某人有帮助。