Sven Haiges
Sven Haiges

Reputation: 2636

Dynamic loading of fields

I am using the graphql-express lib to build a small proof of concept GraphQL server. Let's assume this schema:

const typeDef = `
    type Book {
         id: ID!
         title: String
         author: Author
         likes: Int
    }

    type Author {
         id: String
         name: String
         age: Int
         books: [Book]
    }

    type Query{
         book(id: ID!): Book
    }

This means I will be able to as for a book by ID and the client can chooses which fields are transferred. Let's assume that loading the author is a costly, extra rest call on the server side. So if a client does not request the author, I don't want the resolver function to load the author. Can anyone give an example for the book resolver function does fiures out if it actually has to load the author and only loads it if requested?

thx!

Upvotes: 0

Views: 160

Answers (1)

Asaf Aviv
Asaf Aviv

Reputation: 11760

Resolvers let you define functions that will get executed only when a field is requested.

So we can define function on the Book type for author and on Author type for books, lets assume that author field contains author id and books contains array of book ids

const resolvers = {
  Query: {
    // destruct id from args
    book: (root, { id }) => Book.getBookById(id),
  },
  // When we query for the Book type resolve the author field based on this function
  // if we dont query for the author field this function is not going to run
  // first argument is the parent document/record so we destruct author field
  // which will usually be the author id
  Book: {
    author: ({ author }) => Author.getAuthorById(author),
  },
  // Same as above when we request an Author type run this function
  // when books field is requested
  Author: {
    books: ({ books }) => Book.getBooksByIds(books),
  },
};

Upvotes: 2

Related Questions