2017-05-29 23 views
3

这里是我如何使用GraphQL模式字符串创建模式并将其连接到我的Express服务器:如何使用工会与GraphQL buildSchema

var graphql = require('graphql'); 
var graphqlHTTP = require('express-graphql'); 
[...] 
    return graphqlHTTP({ 
     schema: graphql.buildSchema(schemaText), 
     rootValue: resolvers, 
     graphiql: true, 
    }); 

这是非常基本的使用模块。它运作良好,是相当方便的,直到我要定义一个联盟:

union MediaContents = Photo|Youtube 

type Media { 
    Id: String 
    Type: String 
    Contents: MediaContents 
} 

我发现没有办法,使这项工作,查询内容做的事情必须做,返回正确的对象,但失败的消息Generated Schema cannot use Interface or Union types for execution

使用buildSchema时是否可以使用联合?

回答

6

这正是为什么我们创建了graphql-tools包,就像是一个生产就绪,机械增压版的buildSchemahttp://dev.apollodata.com/tools/graphql-tools/resolvers.html#Unions-and-interfaces

你可以简单地通过工会提供__resolveType方法,像往常一样GraphQL使用工会。 JS:

# Schema 
union Vehicle = Airplane | Car 

type Airplane { 
    wingspan: Int 
} 

type Car { 
    licensePlate: String 
} 

// Resolvers 
const resolverMap = { 
    Vehicle: { 
    __resolveType(obj, context, info){ 
     if(obj.wingspan){ 
     return 'Airplane'; 
     } 
     if(obj.licensePlate){ 
     return 'Car'; 
     } 
     return null; 
    }, 
    }, 
}; 

唯一的变化是,而不是提供您的解析器作为根对象,使用makeExecutableSchema

const graphqlTools = require('graphql-tools'); 
return graphqlHTTP({ 
    schema: graphqlTools.makeExecutableSchema({ 
    typeDefs: schemaText, 
    resolvers: resolvers 
    }), 
    graphiql: true, 
}); 

另请注意,解析器的签名将与常规GraphQL.js样式相匹配,所以它将是(root, args, context)而不是仅当您使用rootValue时得到的(args, context)

+0

好的,这就是我的想法,没有办法用buildSchema来做到这一点。我想在确定添加一个依赖项之前确定:) 还有一个问题:我不太了解resolverMap的语法,是Vehicle在这里定义的内联类(我以前从未见过, m更多的是C++人,并且在JS中一直很困惑:D) –

+1

好的,整合完成,小菜一碟。 非常感谢! –

+1

这是一个很好的答案。正是我在找的东西。 –