GraphQLのインターフェイスとユニオンの違い

インターフェイス(Interfaces)はクエリで共通部分をまとめて記述することができるが、 ユニオン(Union)はできない。 下記の例では、どちらもインラインフラグメント(Inline Fragments)を使っています。インラインフラグメントはクエリの戻り値の型に応じて戻り値のプロパティを変更することができます。

Interfaces

スキーマ

interface Foo {
  propertyA: String
}

type Bar implements Foo {
  propertyA: String
  propertyB: Int
}

type Baz implements Foo {
  propertyA: String
  propertyC: Boolean
}

type Query {
  foo: Foo
}

クエリ

fooがBarの場合はpropertyApropertyBを返します。 fooがBazの場合はpropertyApropertyCを返します。

query {
  foo {
    propertyA
    ... on Bar {
      propertyB
    }
    ... on Baz {
      propertyC
    }
  }
}

Union

スキーマ

type Bar {
  propertyA: String
  propertyB: Int
}

type Baz {
  propertyA: String
  propertyC: Boolean
}

union FooUnion = Bar | Baz

type Query {
  foo: FooUnion
}

クエリ

fooがBarの場合はpropertyApropertyBを返します。 fooがBazの場合はpropertyApropertyCを返します。

query {
  foo {
    ... on Bar {
      propertyA
      propertyB
    }
    ... on Baz {
      propertyA
      propertyC
    }
  }
}