Today I Learned

A Hashrocket project

Casting graphql types with inline fragments

Graphql works with a type system. You ask for fruit and it returns fruit, but that fruit could be a pear or an orange.

(contrived example apologies)

interface Fruit {
  seedless: Boolean
}

type Pear implements Fruit {
  color: String
}

type Apple implements Fruit {
  size: Int
}

So when you ask for fruit, and you want the size of the apple, you have to let graphql know that you want an Apple and are expecting an Apple and while I’m thinking about this as casting the graphql docs call it inline fragments.

  query {
    fruit {
      seedless
      ... on Pear {
        color
      }
      ... on Apple {
        size
      }
    }
  }

The ... is a syntactic element not a writing convention.