如何在graphql中使用带有接口的union类型

时间:2017-08-25 09:48:20

标签: graphql

假设我有联合类型和界面:

type WidgetA implements WidgetInterface {
    id: ID!
    name: String!
    description: String
    type: ???
}

如何定义类型为其中一个联合的窗口小部件?

{}

1 个答案:

答案 0 :(得分:1)

类型可以是联合(type: WidgetType)或特定类型(type: A) - 其中一个是有效的。

这是一个简单的例子,说明如果你在类型中使用union,它会是什么样子:

import { makeExecutableSchema } from 'graphql-tools';

const typeDefs = `
  type Query {
    hello: String
    widgets: [WidgetInterface]
  }
  union WidgetType = A | B | C
  interface WidgetInterface {
    id: ID!
    name: String!
    type: WidgetType!
  }
  type A {
    foo: String
  }
  type B {
    bar: String
  }
  type C {
    baz: String
  }
  type WidgetA implements WidgetInterface {
    id: ID!
    name: String!
    description: String
    type: WidgetType!
  }
`;

const widgets = [
  {
    id: 1,
    name: 'Foo',
    description: '',
    type: {
      baz: 'Baz'
    }
  }
]

const resolvers = {
  Query: {
    hello: (root, args, context) => {
      return 'Hello world!';
    },
    widgets: () => {
      return widgets;
    },
  },
  WidgetInterface: {
    __resolveType: () => 'WidgetA'
  },
  WidgetType: {
    __resolveType: (obj) => {
      if (obj.foo) return 'A'
      if (obj.bar) return 'B'
      if (obj.baz) return 'C'
    }
  }
};

export const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

您可以copy and paste this into Launchpad查看它的实际效果。