Created
October 18, 2021 09:20
-
-
Save tsh-code/9bfc73d545f5b2b83333241f0c0da3e1 to your computer and use it in GitHub Desktop.
Apollo Federation - comments service
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
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