GraphQL - using fragments with interfaces

121 Views Asked by At

I have following union that is described on the server.

type BaseActivity {
 id: Int!
}

type PostActivity implements BaseActivity {
 content: String!
}

type ConcludeActivity implements BaseActivity {
 field: String!
}

type Activity = PostActivity | ConcludeActivity

I try to query on this object, but using fragments.

fragment PostActivityFragment on PostActivity {
 content: string
}

fragment ConcludeActivityFragment on ConcludeActivity {
 content: string
}

query Activities {
 id
 ...PostActivityFragment
 ...ConcludeActivityFragment
}

However, it doesn't work. I'm getting content and field :( The only solution that works is:

query Activities {
 id
 ... on PostActivity {
  content
 }
 ... on ConcludeActivity {
  field
 }
}

But, because of that, I'm losing the benefits of fragments and types.. Any ideas, how to achieve queries on union using fragments?

1

There are 1 best solutions below

1
Syed Hassan Raza On

Try this way

query Activities {
  id
  ... on PostActivity {
    ...PostActivityFragment
  }
  ... on ConcludeActivity {
    ...ConcludeActivityFragment
  }
}

because This way, you're specifying the usage of fragments for each specific type within the union Activity. The ... on TypeName syntax is an inline fragment, and it allows you to specify which fragment should be applied to each concrete type within the union.

Your original attempt with ...PostActivityFragment and ...ConcludeActivityFragment outside of any type didn't work because GraphQL doesn't automatically know which fragment to apply to each type in the union.