Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 3, 2023 03:56 pm GMT

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'));  };

Usage

import { addMiddleware } from 'graphql-add-middleware';export const allowListMutations = ['UserLogin'];addMiddleware(schema, 'Mutation', adminOnlyMutation(allowListMutations));

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


Original Link: https://dev.to/woovi/how-to-create-a-read-only-graphql-server-12ck

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To