Created
November 24, 2019 15:58
-
-
Save johnathan-sewell/02c6679c42b29f0999c08be819b9e3df to your computer and use it in GitHub Desktop.
GraphQL server showing circular relationship
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 authors = [ | |
{ id: 1, name: "J.K. Rowling" }, | |
{ id: 2, name: "Michael Crichton" } | |
]; | |
const books = [ | |
{ | |
authorId: 1, | |
title: "Harry Potter and the Chamber of Secrets" | |
}, | |
{ | |
authorId: 1, | |
title: "Harry Potter and the Philosphers Stone" | |
}, | |
{ | |
authorId: 2, | |
title: "Jurassic Park" | |
} | |
]; | |
const schema = gql` | |
type Query { | |
getAuthor(id: Int): Author | |
} | |
type Book { | |
title: String | |
author: Author | |
} | |
type Author { | |
name: String | |
books: [Book] | |
} | |
`; | |
const resolvers = { | |
Query: { | |
getAuthor(parent, args, context, info) { | |
console.log("resolving getAuthor", parent, args); | |
return authors.find(a => a.id === args.id); | |
} | |
}, | |
Author: { | |
name(parent, args) { | |
return parent.name; | |
}, | |
books(parent, args) { | |
return books.filter(book => book.authorId === parent.id); | |
} | |
}, | |
Book: { | |
title(parent, args) { | |
return parent.title; | |
}, | |
author(parent, args) { | |
return authors.find(author => author.id === parent.authorId); | |
} | |
} | |
}; | |
// The ApolloServer constructor requires two parameters: your schema | |
// definition and your set of resolvers. | |
const server = new ApolloServer({ typeDefs: schema, resolvers, tracing: true }); | |
// The `listen` method launches a web server. | |
server.listen().then(({ url }) => { | |
console.log(`🚀 Server ready at ${url}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample query