Ryan Ro
Ryan Ro

Reputation: 394

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?

Upvotes: 1

Views: 1623

Answers (2)

mohit sirova
mohit sirova

Reputation: 1

NestJS provides different types of contexts depending on the type of incoming request. For HTTP requests, the context includes the traditional Request object from Express or Fastify. However, for GraphQL requests, the context is encapsulated within the GqlExecutionContext.

Upvotes: 0

Jay McDoniel
Jay McDoniel

Reputation: 70061

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

Upvotes: 7

Related Questions