类型可以是联合(type: WidgetType
)或特定类型(type: A
) - 任一方有效。
这里有一个如何可能看起来像如果您使用的联盟类型一个简单的例子:
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看到它在行动。
从你的问题中不清楚你问的是什么。在这种情况下什么是“小部件”?除了A,B和C以外,所有类型定义都已经存在于您的模式中,那么您究竟想要定义什么?或者你在问如何实现这个模式的解析器来使它工作? –
我的问题是关于创建一个实现接口的类型。更新了查询。 –