2017-08-25 172 views
0

可以说我有一个联合类型和接口:如何使用union类型的接口,在graphql

union WidgetType = A | B | C 
interface WidgetInterface { 
    id: ID! 
    name: String! 
    type: WidgetType! 
} 

我如何定义一个小部件,其中的类型是工会的一个?

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

从你的问题中不清楚你问的是什么。在这种情况下什么是“小部件”?除了A,B和C以外,所有类型定义都已经存在于您的模式中,那么您究竟想要定义什么?或者你在问如何实现这个模式的解析器来使它工作? –

+0

我的问题是关于创建一个实现接口的类型。更新了查询。 –

回答

1

类型可以是联合(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看到它在行动。

+0

但是,这并不意味着'WidgetA'可以来自任何类型。我认为有一种方法可以使小部件类型修复。 –

+0

如果你需要修复它,为什么不只是'输入:A'或者你需要的类型?仅仅因为它是工会的一部分并不意味着它不能单独使用。 –

+0

感谢您的澄清。 –