How to use joins with GraphQL buildSchema
This is how I use a GraphQL schema string to create a schema and attach it to my Express server:
var graphql = require('graphql');
var graphqlHTTP = require('express-graphql');
[...]
return graphqlHTTP({
schema: graphql.buildSchema(schemaText),
rootValue: resolvers,
graphiql: true,
});
It's all very simple to use modules. It works well and is pretty convenient, as long as I don't want to define a union:
union MediaContents = Photo|Youtube
type Media {
Id: String
Type: String
Contents: MediaContents
}
I haven't found a way to make this work, the content request does what it should do, returns the correct object, but Generated Schema cannot use Interface or Union types for execution
doesn't work with the message .
Can you use unions at all when using buildSchema?
source to share
This is why we have created a package graphql-tools
that looks like the finished supercharged version buildSchema
: http://dev.apollodata.com/tools/graphql-tools/resolvers.html#Unions-and-interfaces
You can simply use unions by providing a method __resolveType
in the union as usual with 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;
},
},
};
The only change is that instead of providing your resolvers as the root object, use makeExecutableSchema
:
const graphqlTools = require('graphql-tools');
return graphqlHTTP({
schema: graphqlTools.makeExecutableSchema({
typeDefs: schemaText,
resolvers: resolvers
}),
graphiql: true,
});
Also note that the signature of the resolvers will follow the regular style of GraphQL.js, so it will (root, args, context)
instead just (args, context)
be what it gets when you use rootValue
.
source to share