graphqlapolloapollo-client

apollo graphql: how to query union type fields


I have the following schema for my server:

const typeDefs = `#graphql
  type DeliveryType {
    delivery: String!
    deliveryStreetNumberId: String!
    pickupLocationId: String!
    storeId: String!
  }

  type PickupType {
    storeId: String!
  }

  union OrderType = DeliveryType | PickupType

  type Query { 
    getOrderType(userId: String!): OrderType
  }

And then I have the following query definitions on my FE:

export const GET_ORDER_TYPE = gql`
  query getOrderType($userId: String!) {
    getOrderType(userId: $userId) {
      delivery
      deliveryStreetNumberId
      pickupLocationId
      storeId
    }
  }
`;

However, I am getting the following errors:

graphQLErrors: [ { message: 'undefined: Cannot query field "delivery" on type "OrderType". Did you mean to use an inline fragment on "DeliveryType"?' }, { message: 'undefined: Cannot query field "deliveryStreetNumberId" on type "OrderType". Did you mean to use an inline fragment on "DeliveryType"?' }, { message: 'undefined: Cannot query field "pickupLocationId" on type "OrderType". Did you mean to use an inline fragment on "DeliveryType"?' }, { message: 'undefined: Cannot query field "storeId" on type "OrderType". Did you mean to use an inline fragment on "DeliveryType" or "PickupType"?' } ]

I thought that I could query all the fields from the union and then get null where the field is not available?

Is there another way to do this, or what would be the conventional way to handle this?


Solution

  • You need to specify which type to get the non-common fields from. In your case:

    query getOrderType($userId: String!) {
      getOrderType(userId: $userId) {
        ...on DeliveryType {
          delivery
          deliveryStreetNumberId
          pickupLocationId
        }
        storeId
      }
    }
    

    Documentation