Search code examples
restgraphqlnestjsauth-guard

NestJS AuthGuard that handles both GraphQL and REST


According to the docs, in order to use AuthGuard for the auth of GraphQL resolvers, we have to override getRequest method like this:

  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
  }

Most of my APIs use GraphQL, but the others use REST endpoints for handling file uploads. (I referred to this) Now, I'm using two AuthGuards. One is for GraphQL in which I overrode getRequest like above. The other one is for REST whose code is completely the same except getRequest (this time I did not override it) and the way to extract user object from the request after calling canActivate.

GraphQL:

// getRequest is overridden
const user: User = this.getRequest(context).user;

REST:

// getRequest is NOT overridden
const { user } = context.switchToHttp().getRequest();

Is there any method I can try to combine these two AuthGuards into one?


Solution

  • Why not have something like this for the getRequest method:

    getRequest(context: ExecutionContext) {
      if (context.getType<ContextType | 'graphql'>() === 'graphql') {
        return GqlExecutionContext.create(context).getContext().req;
      }
      return context.switchToHttp().getRequest();
    }
    

    And now you just need the one guard. req.user will be populated the same whether using GraphQL or REST