Last active
July 24, 2019 22:32
-
-
Save ziplizard/60aeea4cb654d4ed7f6af1d7bf652151 to your computer and use it in GitHub Desktop.
GraphQL Federation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Service A | |
const resolvers = { | |
User: { | |
id(parent) { | |
return parent.Id; | |
}, | |
}, | |
}; | |
const typeDefs = gql` | |
interface Node { | |
id: ID! | |
} | |
type User implements Node @key(fields: "id") { | |
id: ID! | |
internalId: ID! | |
type: String! | |
} | |
`; | |
const server = new ApolloServer({ | |
schema: buildFederatedSchema([ | |
{ | |
typeDefs, | |
resolvers, | |
}, | |
]), | |
}); | |
// Service B | |
const typeDefs = gql` | |
extend type Query { | |
me: User | |
} | |
extend type User @key(fields: "id") { | |
id: ID! @external | |
name: String | |
username: String | |
} | |
`; | |
const resolvers = { | |
Query: { | |
me() { | |
return { id: 'RW1wbG95ZWU6MjA2NDIy', name: 'Matt Myers', username: 'mmyers' }; | |
}, | |
}, | |
}; | |
const server = new ApolloServer({ | |
schema: buildFederatedSchema([ | |
{ | |
typeDefs, | |
resolvers, | |
}, | |
]), | |
}); |
Just updated gist with the latest. No longer getting errors, but it's not returning the name
. Ideas? I'm getting close.
I got it working. Thanks so much!
Edit: Oops, seems like you figured it out on your own. Here's my findings anyway 😄
Hi @ziplizard, I've managed to get this working:
Service A
const resolvers = { };
const typeDefs = gql`
interface Node {
id: ID!
}
type User implements Node @key(fields: "id") {
id: ID!
internalId: ID!
type: String!
}
`;
Service B
const typeDefs = gql`
extend type Query {
me: User
}
extend type User @key(fields: "id") {
id: ID! @external
name: String
username: String
}
`;
const resolvers = {
Query: {
me() {
return { id: 'RW1wbG95ZWU6MjA2NDIy' };
},
},
User: {
__resolveReference(object) {
// find user by id
if (object.id === 'RW1wbG95ZWU6MjA2NDIy') {
return {
...object,
name: 'Matt Myers',
username: 'mmyers'
}
}
}
}
};
I think the key is providing User.__resolveReference
in every service that adds fields to User
. Notice how I didn't include it in Service A though because in that service User
only has id
. If it has more fields that were not included in the key I believe you would need to include User.__resolveReference
in that resolver as well.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Then doing:
And get the following error:
GraphQLError: Unknown type "_Any".
And:
Cannot query field "_entities" on type "Query".