graphqlgraphql-tools

Using composeResolvers with an array of resolvers


Is it possible to pass an array of resolvers into composeResolvers from "@graphql-tools/resolvers-composition". If I do something like composeResolvers(authorsResolvers, resolversComposition); it works however if I try to pass in all my resolvers, composeResolvers(resolvers, resolversComposition);, it doesn't work.

const rootResolver = {};

const resolvers = [rootResolver, authorsResolvers, booksResolvers];

const isAuthenticated =
  () =>
  (next: any) =>
  async (root: any, args: any, context: any, info: any) => {
    if (!context.currentUser) {
      throw new Error("You are not authorized");
    }
    return next(root, args, context, info);
  };

const resolversComposition = {
  "*.*": [isAuthenticated()],
};

const composedResolvers = composeResolvers(resolvers, resolversComposition);

export default composedResolvers;

Solution

  • No, composeResolvers expects an object as the first argument. If all valid resolver objects, you could do something like this:

    const resolvers = {...rootResolver, ...authorsResolvers, ...booksResolvers};
    

    But make sure to do the necessary adjustments in case they have overlapping attributes, otherwise the last one will override the former.