DEV Community

Cover image for How to create a read-only GraphQL server
Sibelius Seraphini for Woovi

Posted on

How to create a read-only GraphQL server

At Woovi, we have a console/back-office to manage all our operations. We would like to give access to it for all our developers to make their support life easier, but we do not want to reduce our security.
Our console access is permission based, each user has some roles that give them access to some features.
If a user does not have any role, we want to make sure it can only read the data, but they can't modify any data.

Using GraphQL middlewares to make a read-only API

GraphQL provides some meta information where we can check if the request is a query or mutation and which mutation is being requested.

We added a middleware to intercept a GraphQL operation that checks if the request is a mutation and the user has the permission to execute them.

The code is shown below:

export const adminOnlyMutation =
  (allowListMutations: string[] = []) =>
  (
    root: any,
    args: { [argName: string]: any },
    context: GraphQLContext,
    info: GraphQLResolveInfo,
    next: () => void,
  ) => {
    const mutationType = info.schema.getMutationType();

    if (allowListMutations.includes(info.fieldName)) {
      return next();
    }

    if (!mutationType) {
      return next();
    }

    if (context?.user?.roles?.includes('ADMIN')) {
      return next();
    }

    const fields = info.returnType.getFields();

    if (fields.error && fields.error.type === GraphQLString) {
      return {
        error: context.t('User not allowed'),
      };
    }

    throw new Error(context.t('User not allowed'));
  };
Enter fullscreen mode Exit fullscreen mode

Usage

import { addMiddleware } from 'graphql-add-middleware';

export const allowListMutations = ['UserLogin'];

addMiddleware(schema, 'Mutation', adminOnlyMutation(allowListMutations));

Enter fullscreen mode Exit fullscreen mode

In Conclusion

GraphQL middleware is a powerful way to modify your GraphQL schema.
Making a read-only API using REST would take more work, as you need to manage many endpoints.
You can do that in a few lines of code in GraphQL.


Woovi
Woovi is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.

If you want to work with us, we are hiring!


Photo by Roman Kraft on Unsplash

Top comments (0)