0.0.26 • Published 4 months ago

buro26-strapi-graphql v0.0.26

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
4 months ago

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.

This plugin is compatible with both Strapi v4 and Strapi v5.

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:

MethodDescription
initCalled when the extension is initialized
typesReturns an array of GraphQL types
typeDefsReturns a string with the type definition in SDL
resolversReturns an object with resolvers
resolversConfigReturns 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);
          }
        ]
      }
    };
  }
}));

Fluent Builder Pattern

The plugin also supports a builder pattern so that you can configure your extension using a fluent API. This is achieved by calling createGraphQLExtension() with no arguments. For example, you can write:

export default createGraphQLExtension()
  .init(() => {
    // Initialization logic here...
  })
  .typeDefs(`
    extend type Query {
      hello: String
    }
  `)
  .resolvers({
    Query: {
      hello: () => 'Hello from builder!'
    }
  });

In this pattern, createGraphQLExtension() detects that no argument was passed and returns a builder. The builder exposes methods like .init(), .typeDefs(), .types(), .plugins(), .resolvers(), and .resolversConfig() so you can chain calls and define your extension inline.

Shorter way to define a new field

The createGraphQLFieldBuilder() function provides a fluent builder API to create a single GraphQL field extension using Nexus. It simplifies the process of extending the GraphQL schema by letting you define the field's name, arguments, output type, resolver, and resolver configuration in a chainable way.

The builder pattern ensures that you only need to specify the necessary parts, and the extension is automatically registered using the provided settings. This approach minimizes boilerplate code while ensuring consistency across your GraphQL extensions.

Below is an example of how to define a new field using the builder pattern. This example creates a new query field called helloWorld that takes a non-null name argument and returns a non-null String.

import { createGraphQLFieldBuilder } from "buro26-strapi-graphql";
import { nonNull, stringArg } from 'nexus';

export default createGraphQLFieldBuilder('Query')
  .fieldName('helloWorld')
  .args({
    name: nonNull(stringArg()),
  })
  .outputType(nonNull('String'))
  .resolver(async (parent, args, ctx) => {
    return `Hello World ${args.name}`;
  })
  .resolverConfig({
    auth: false,
  });

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.

shadowCRUD

This function is a typesafe utility function to create shadow CRUD operations for a content type. It will create the CRUD operations for the content type and return the shadow CRUD object.

import { createGraphQLExtension, shadowCRUD } from 'buro26-strapi-graphql';

export default createGraphQLExtension((strapi) => ({

  init() {
    shadowCRUD('api::article.article')
      .disableActions(['create', 'update', 'delete']);

    shadowCRUD('api::category.category')
      .field('title')
      .disable();
  }

}));

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!

0.0.24

4 months ago

0.0.25

4 months ago

0.0.26

4 months ago

0.0.23

9 months ago

0.0.20

10 months ago

0.0.21

10 months ago

0.0.22

10 months ago

0.0.16

11 months ago

0.0.17

11 months ago

0.0.18

11 months ago

0.0.19

10 months ago

0.0.11

11 months ago

0.0.12

11 months ago

0.0.13

11 months ago

0.0.14

11 months ago

0.0.15

11 months ago

0.0.10

12 months ago

0.0.9

12 months ago

0.0.8

12 months ago

0.0.7

12 months ago

0.0.6

12 months ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago