Skip to content

Instantly share code, notes, and snippets.

@ziplizard
Last active July 24, 2019 22:32
Show Gist options
  • Save ziplizard/60aeea4cb654d4ed7f6af1d7bf652151 to your computer and use it in GitHub Desktop.
Save ziplizard/60aeea4cb654d4ed7f6af1d7bf652151 to your computer and use it in GitHub Desktop.
GraphQL Federation
// 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,
},
]),
});
@ziplizard
Copy link
Author

Then doing:

query {
  me {
    name
  }
}

And get the following error: GraphQLError: Unknown type "_Any".
And: Cannot query field "_entities" on type "Query".

@ziplizard
Copy link
Author

Just updated gist with the latest. No longer getting errors, but it's not returning the name. Ideas? I'm getting close.

@ziplizard
Copy link
Author

I got it working. Thanks so much!

@jasonpaulos
Copy link

jasonpaulos commented Jul 24, 2019

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