1

In a child resolver in GraphQL, I want to use an API to get the data. Example schema and resolver:

import { gql,ApolloServer } from "apollo-server";

const typeDefs = gql`
  type Review{
    id: String!
    rating: String!
    comments: [String]
  }
  type Book {
    id: String!
    name: String!
    review: Review
  }
  type Query {
    getBooks: [Book]
  }
`;

(async function () {
    const server = new ApolloServer({
        typeDefs,
        resolvers: {
          Query: {
            getBooks: () => {
              return [{
                id: '1',
                name: 'Abc'
              },{
                id: '2',
                name: 'Def'
              }];
            },
          },
          Book: {
            review: async () => {
              // Make API call to get the review data.
              return {
                id: '1',
                rating: '4',
                comments: ['Great book', 'A decent read.']
              };
            }
          },
        }
    });

    await server.listen().then(({url}) => {
      console.log(url)
    });
})();

The problem is that if the result contains 10 books, the review API will be called 10 times to get the corresponding data. The API supports receiving a list of IDs in the request and returning a list of review objects back. Is there a way to make resolver call the API only once to get the data for all of the books? Can this be implemented using Apollo federation? Thanks.

0 Answers0