Search code examples
node.jsgraphql-jsapollo-server

"Abstract type X must resolve to an Object type at runtime for field Query.user with value


this my code

schema

gql`
  type Query {
    user: X!
  }
  type User {
    name: String!
  }
  type Time {
    age: Int!
  }
  union X = User | Time
`;

resolvers

{
  X: {
    __resolveType: obj => {
      if (obj.name) return { name: "Amasia" };
      if (obj.age) return { age: 70 };
      return null;
    }
  },
  Query: {
    user: () => {
      return {
        name: "Amasia"
      };
    }
  }
}

request

query {
user{
  ... on User {
    name
  }
  ... on Time {
    age
  }
}
}

When I make a request do I get Error

"Abstract type X must resolve to an Object type at runtime for field Query.user with value { name: \"Amasia\" }, received \"{ name: \"Amasia\" }\". Either the X type should provide a \"resolveType\" function or each possible type should provide an \"isTypeOf\" function."

What is the reason.?


Solution

  • The resolveType function should return a string with the name of the concrete type the abstract type should resolve to. You are returning an object, not string. In this case, you should return "User" or "Time".