24

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.?

Edgar
  • 6,022
  • 8
  • 33
  • 66

2 Answers2

20

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".

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Thank you for this solution! it helped me! I also wanted to add on. If you have the resolveType setup correctly and still getting the error, check your Query's returning data. I was looking for obj.title but turns out, the obj was obj.Items with array, so couldn't find title property. – il0v3d0g Nov 01 '21 at 02:39
2

Simply add the __typename to the object to resolve it:

 {
  Query: {
    user: () => {
      return {
        __typename: 'User',
        name: "Amasia"
      };
    }
  }
}
Ericgit
  • 6,089
  • 2
  • 42
  • 53