Skip to content

Instantly share code, notes, and snippets.

@johnathan-sewell
Created November 24, 2019 15:58
Show Gist options
  • Save johnathan-sewell/02c6679c42b29f0999c08be819b9e3df to your computer and use it in GitHub Desktop.
Save johnathan-sewell/02c6679c42b29f0999c08be819b9e3df to your computer and use it in GitHub Desktop.
GraphQL server showing circular relationship
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}`);
});
@johnathan-sewell
Copy link
Author

johnathan-sewell commented Nov 24, 2019

Sample query

  getAuthor(id: 1) {
    name
    books {
      title
      author {
        name
        books {
          title
          author {
            name
            books {
              title
            }
          }
        }
      }
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment