GraphQL Union Types and GraphQL Tools

22 Nov 2021

const typeDefs = `
  type Query {
    tracks: [Track]
    videos: [Video]
    images: [Image]
    feed: [FeedItem!]!
  }

  union FeedItem = Track | Video | Image

  type Track {
    duration: Int
    format: TrackFormat
  }

  type Video {
    length: Int
    format: VideoFormat
  }

  type Image {
    width: Int
    height: Int
    format: ImageFormat
  }

  enum TrackFormat {
    WAV
    MP3
    AAC
  }

  enum VideoFormat {
    AVI
    MP4
    M4V
  }

  enum ImageFormat {
    PNG
    JPG
    TIFF
  }
`;
const resolvers = {
  Query: {
    tracks: () => tracks,
    videos: () => videos,
    images: () => images,
    feed: () => [
      ...tracks,
      ...videos,
      ...images,
      {
        width: 500,
        height: 350,
        format: "TIFF",
      },
    ],
  },
  FeedItem: {
    __resolveType: (object) => {
      if (object.duration) {
        return "Track";
      }
      if (object.length) {
        return "Video";
      }
      if (object.width) {
        return "Image";
      }
      return null;
    },
  },
};