Skip to content

Instantly share code, notes, and snippets.

@tsh-code
Created October 18, 2021 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsh-code/9bfc73d545f5b2b83333241f0c0da3e1 to your computer and use it in GitHub Desktop.
Save tsh-code/9bfc73d545f5b2b83333241f0c0da3e1 to your computer and use it in GitHub Desktop.
Apollo Federation - comments service
const { ApolloServer, gql } = require("apollo-server");
const { buildSubgraphSchema } = require("@apollo/federation");
const comments = [
{
id: "1",
post: { id: "1" },
text: "Super Cool",
},
{
id: "2",
post: { id: "1" },
text: "Gr8!",
},
];
const typeDefs = gql`
type Comment @key(fields: "id") {
id: ID!
post: Post
text: String
}
extend type Post @key(fields: "id") {
id: ID! @external
comments: [Comment]
}
`;
const resolvers = {
Comment: {
_resolveReference(object) {
return comments.find((comment) => comment.id === object.id);
},
},
Post: {
comments(post) {
return comments.filter((comment) => comment.post.id === post.id);
},
},
};
const server = new ApolloServer({
schema: buildSubgraphSchema({
typeDefs,
resolvers,
}),
});
server.listen({ port: 5002 }).then(({ url }) => console.log(`Comments service ready at ${url}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment