npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

buro26-strapi-graphql

v0.0.23

Published

Extension and utilities for Strapi GraphQL

Downloads

301

Readme

Strapi GraphQL Extension

Extension and utilities for Strapi GraphQL API. This plugin adds additional features to the Strapi GraphQL plugin such as co-location of GraphQL schema and resolvers, field overriding, and field authorization.

This let's you define your GraphQL schema and resolvers in the content-type directory, making it easier to manage and maintain your GraphQL API.

Getting started

npm i buro26-strapi-graphql

Usage

Configure Strapi GraphQL plugin

To be able to use this plugin, you will first need to configure the Strapi GraphQL plugin.

Enable plugin

Add plugin in ./config/plugins.js/ts in your Strapi project.

export default () => ({
  // ...
  'burotwosix-graphql-plugin': {
    enabled: true
  }
  // ...
})

Create a new GraphQL Extension

To create a new GraphQL extension, create a folder named graphql in the content-type directory or within the extensions folder (in case of extending a plugin). Inside the graphql folder you can create files with any name. This plugin will scan the graphql folder register your extensions with Strapi.

From each file create a default export that uses th createGraphQLExtension factory function. This function takes a function as an argument that will receive the Strapi instance and should return an object with the following methods:

| Method | Description | |-----------------|--------------------------------------------------| | init | Called when the extension is initialized | | types | Returns an array of GraphQL types | | typeDefs | Returns a string with the type definition in SDL | | resolvers | Returns an object with resolvers | | resolversConfig | Returns an object with resolver configuration |

The functions you can implement follow the pattern of the Strapi customization options: https://docs.strapi.io/dev-docs/plugins/graphql#customization. The return values here will be registered as-is with Strapi in the register hook.

import { createGraphQLExtension } from 'buro26-strapi-graphql';
import { extendType, nonNull, stringArg } from 'nexus';

export default createGraphQLExtension(strapi => ({

  init() {
    // e.g. disable actions
    strapi
      .plugin('graphql')
      .service('extension')
      .shadowCRUD('api::my-type.my-type')
      .disableActions(['find', 'findOne', 'create', 'update', 'delete']);
  },

  typeDefs() {
    return `
      type HelloWorldResponse {
        greeting: String!
      }
    `;
  },

  types() {
    return [
      // Extend an existing type
      extendType({
        type: 'MyType',
        definition(t) {
          t.field('foo', {
            type: 'Boolean',
            resolve: async (root) => {
              return false;
            }
          });
          t.field('bar', {
            type: 'Boolean',
            resolve: async (root) => {
              return false;
            }
          });
        }
      }),

      // Create a new query
      extendType({
        type: 'Query',
        definition(t) {
          t.field('helloWorld', {
            type: 'HelloWorldResponse',
            args: {
              greeting: nonNull(stringArg())
            },
            // either resolve here or add it in resolvers method
            resolve: async (root, args) => {
              // resolve logic
            }
          });
        }
      })
    ];
  },

  resolvers() {
    return {
      Query: {
        // Override an existing query
        helloWorld: async (root, args) => {
          // resolve logic
        }
      },
      Mutation: {
        // Override an existing mutation
        updateMyType: async (root, args) => {
          // resolve logic
        }
      }
    };
  },

  resolversConfig() {
    return {
      'Query.helloWorld': {
        policies: [
          async ({ state, args }, { strapi }) => {
            // Validate request
          }
        ],
        middlewares: [
          async (next, root, args, context, info) => {
            // Do something here

            return next(root, args, context, info);
          }
        ]
      }
    };
  }
}));

Overriding a field

Sometimes you will need to override a field in an existing type. You can do this by extending the type and adding the field again. The field will be overridden with the new field definition. To make this easier we added a helper function overrideField that will make this easier. The helper method also automatically generates a resolver for the field.

The overrideField function needs the content type and fieldName to be able to resolve the field type and the resolver. The authorize function is optional and can be used to authorize the field. The resolve function is also optional and can be used to resolve the field.

import { createGraphQLExtension, overrideField } from 'buro26-strapi-graphql';
import { extendType } from 'nexus';

export default createGraphQLExtension(strapi => ({
  types() {
    return [
      // Extend an existing type
      extendType({
        type: 'MyType',
        definition(t) {
          overrideField<MyContentType>(t, {
            contentTypeName: 'api::my-type.my-type',
            fieldName: 'myField',
            description: 'My field description',
            authorize: async (root, args, context) => {
              // Authorization logic
              return true;
            },
            resolve: async (root) => {
              // Resolver is optional
              return false;
            }
          });
        }
      })

    ];
  }
}));

Add authorization to an existing field

By default Strapi GraphQL does not support field level authorization. This plugin adds support for field level authorization. You can add authorization to an existing field by using the before mentioned overrideField function. The authorize function will be called before the field is resolved. If the authorize function returns false the field will not be resolved and an error will be thrown.

If you decide not to pass the resolve function and only the authorize function, the field will be resolved by the default resolver generated by the plugin.

import { createGraphQLExtension, overrideField } from 'buro26-strapi-graphql';
import { extendType } from 'nexus';

export default createGraphQLExtension(strapi => ({
  types() {
    return [
      // Extend an existing type
      extendType({
        type: 'MyType',
        definition(t) {
          overrideField<MyContentType>(t, {
            contentTypeName: 'api::my-type.my-type',
            fieldName: 'myField',
            authorize: async (root, args, context) => {
              // Decide if the user is authorized to access the field
              return true;
            }
          });
        }
      })

    ];
  }
}));

Field middleware

You can add middleware to a specific field, similarly to adding authorization. Each field can have multiple middlewares.

This can be useful when you want to add some logic before or after the field is resolved. E.g. logging, caching, response parsing, etc.

import { createGraphQLExtension, overrideField } from 'buro26-strapi-graphql';
import { extendType } from 'nexus';

export default createGraphQLExtension(strapi => ({
  types() {
    return [
      // Extend an existing type
      extendType({
        type: 'MyType',
        definition(t) {
          t.field('myField', {
            type: 'MyFieldType',
            extensions: {
              middlewares: [
                next => async (root, args, context, info) => {
                  // Do something before the field is resolved

                  const res = await next(root, args, context, info);

                  // Do something after the field is resolved

                  return res;
                }
              ]
            },
            resolve: async (root) => {
              // Resolver is optional
            }
          })
          overrideField<MyContentType>(t, {
            contentTypeName: 'api::my-type.my-type',
            fieldName: 'myField',
            extensions: {
              middlewares: [
                next => async (root, args, context, info) => {
                  // Do something before the field is resolved

                  const res = await next(root, args, context, info);

                  // Do something after the field is resolved

                  return res;
                }
              ]
            }
          });
        }
      })

    ];
  }
}));

Utility functions

The plugin also provides utility functions to help you resolve entities and collections. These functions are useful when you need to resolve entities and collections in your resolvers.

resolveEntity

The resolveEntity function can be used to resolve an entity by id. The function takes the content type name and an object with all the resolve args passed the resolver function. The function will return the resolved entity as EntityResponse.

import { createGraphQLExtension, overrideField, resolveEntity } from 'buro26-strapi-graphql';
import { extendType } from 'nexus';

export default createGraphQLExtension(strapi => ({
  types() {
    return [
      // Extend an existing type
      extendType({
        type: 'MyType',
        definition(t) {
          t.field('myFields', {
            type: 'MyFieldEntityResponse',
            resolve: async (parent, args, context, info) => {
              // Do something, and resolve the entit
              return resolveEntity<MyContentType>('api::my-content-type.my-content-type', {
                args: {
                  id: 'the id here',
                },
                parent,
                context,
                info,
              })
            }
          });
          overrideField<MyContentType>(t, {
            contentTypeName: 'api::my-type.my-type',
            fieldName: 'myOtherField',
            resolve: async (parent, args, context, info) => {
              // Do something, and resolve the entit
              return resolveEntity<MyContentType>('api::my-content-type.my-content-type', {
                args: {
                  id: 'the id here',
                },
                parent,
                context,
                info,
              })
            }
          });
        }
      })

    ];
  }
}));

resolveEntityRelation

The resolveEntityRelation function can be used to resolve an entity by id. The function takes the content type name and an object with all the resolve args passed the resolver function. The function will return the resolved entity as EntityResponse.

import { createGraphQLExtension, overrideField, resolveEntityRelation } from 'buro26-strapi-graphql';
import { extendType } from 'nexus';

export default createGraphQLExtension(strapi => ({
  types() {
    return [
      // Extend an existing type
      extendType({
        type: 'MyType',
        definition(t) {
          t.field('myFields', {
            type: 'MyFieldEntityResponse',
            resolve: async (parent, args, context, info) => {
              // Do something, and resolve the entit
              return resolveEntityRelation<MyContentType>('api::my-content-type.my-content-type', {
                args: {
                  id: 'the id here',
                },
                parent,
                context,
                info,
              })
            }
          });
          overrideField<MyContentType>(t, {
            contentTypeName: 'api::my-type.my-type',
            fieldName: 'myOtherField',
            resolve: async (parent, args, context, info) => {
              // Do something, and resolve the entit
              return resolveEntityRelation<MyContentType>('api::my-content-type.my-content-type', 'myRelationField', {
                args,
                parent, // needs to have the id field populated
                context,
                info,
              })
            }
          });
        }
      })

    ];
  }
}));

resolveEntityCollection

The resolveEntityCollection function can be used to resolve a collection of entities. The function takes the content type name and an object with all the resolve args passed the resolver function. The function will return the resolved collection as EntityCollectionResponse.

import { createGraphQLExtension, overrideField, createEntityCollectionResolver } from 'buro26-strapi-graphql';
import { extendType } from 'nexus';

export default createGraphQLExtension(strapi => ({
  types() {
    return [
      // Extend an existing type
      extendType({
        type: 'MyType',
        definition(t) {
          t.field('myFields', {
            type: 'MyFieldEntityResponseCollection',
            resolve: async (parent, args, context, info) => {
              // Do something, and resolve the entity
              const resolver = createEntityCollectionResolver<MyContentType>('api::my-content-type.my-content-type');
              return resolver({
                args,
                parent,
                context,
                info,
              })
            }
          });
          overrideField<MyContentType>(t, {
            contentTypeName: 'api::my-type.my-type',
            fieldName: 'myOtherField',
            resolve: async (parent, args, context, info) => {
              // Do something, and resolve the entity
              const resolver = createEntityCollectionResolver<MyContentType>('api::my-content-type.my-content-type');
              return resolver({
                args,
                parent,
                context,
                info,
              })
            }
          });
        }
      })

    ];
  }
}));

resolveEntityRelationCollection

This function has a similar API as createEntityRelationCollectionResolver but is used to resolve a collection of entities from a relational field on the provided content type. The only difference is that the resolvers first argument is the relation field name that should be resolved.

toEntityResponse

This function is a typesafe response builder for a single entity. It takes the entity and the content type name and will return an EntityResponse.

This function is re-exported from the Strapi GraphQL plugin.

toEntityCollectionResponse

This function is a typesafe response builder for a collection of entities. It takes the entities and the content type name and will return an EntityCollectionResponse.

This function is re-exported from the Strapi GraphQL plugin.

resolveArgs

This function is a typesafe utility function to resolve the args passed to the resolver function. It will transform the graphql args into args that can be passed to the entityManager.

This function is re-exported from the Strapi GraphQL plugin.

Test and Deploy

Running tests

To run tests, run the following command:

bun test

Contributing

Wish to contribute to this project? Pull the project from the repository and create a merge request.

Authors and acknowledgment

Buro26 - https://buro26.digital
Special thanks to all contributors and the open-source community for their support and contributions.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project status

The project is currently in active development. We are continuously working on adding new features and improving the existing ones. Check the issues section for the latest updates and planned features.

Feel free to reach out if you have any questions or suggestions!