GraphQL custom resolver in V4

After a little digging, I found it very straightforward to set up a custom resolver on a GraphQL type. Here’s a loose example. Even though this topic is listed as solved. I’m replying here because it seems like people are having issues and this is the first result I found in Google.

Here is a sample src/index.js

'use strict';

module.exports = {
  /**
   * An asynchronous register function that runs before
   * your application is initialized.
   *
   * This gives you an opportunity to extend code.
   */
  register({ strapi }) {
    const extensionService = strapi.plugin('graphql').service('extension');

    const extension = ({}) => ({
      typeDefs: `
        type YourType {
          customResolver: [OtherType!]!
        }
      `,
      resolvers: {
        YourType: {
          customResolver: async (parent, args) => {
            const entries = await strapi.entityService.findMany('api::other-type.other-type', {});
            return entries;
          }
        }
      }
    })
    extensionService.use(extension);
  },

  /**
   * An asynchronous bootstrap function that runs before
   * your application gets started.
   *
   * This gives you an opportunity to set up your data model,
   * run jobs, or perform some special logic.
   */
  bootstrap(/*{ strapi }*/) {},
};

I hope this helps you out. Let me know if this doesn’t work for you or if you have any questions.

5 Likes