NestJS中如何在@ResolveProperty守卫中获取HTTP请求对象?
Hey there, great question! This is indeed expected behavior in NestJS 5.x when working with GraphQL @ResolveProperty guards, but there's a straightforward fix to get access to the full Express request object.
Why this happens
In NestJS 5.x's GraphQL implementation, the context passed to field resolvers (those decorated with @ResolveProperty) defaults to the return value of the parent resolver (your root Query), rather than retaining the original HTTP request context. That's why context.switchToHttp().getRequest() returns the parent Query result instead of the Express request—because the HTTP context layer gets overwritten at the field resolution stage.
How to get the full Express request in your guard
To fix this, you need to explicitly pass the Express request object into the GraphQL context during module setup, so it's available to all resolvers (including field resolvers):
Update your GraphQLModule configuration
When initializingGraphQLModule.forRoot(), define a custom context factory that attaches the Express request to the GraphQL context:import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; @Module({ imports: [ GraphQLModule.forRoot({ typePaths: ['./**/*.graphql'], // Explicitly pass the request to the GraphQL context context: ({ req }) => ({ req }), }), ], }) export class AppModule {}Adjust your guard to access the request directly
Instead of relying onswitchToHttp(), useGqlExecutionContextto extract the request from the GraphQL context directly:import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; @Injectable() export class YourRoleGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const gqlCtx = GqlExecutionContext.create(context); const req = gqlCtx.getContext().req; // Now you have the full Express request // Your role validation logic here (e.g., check req.user.role) return req.user?.role === 'admin'; } }
Quick note for future reference
This context handling issue was fixed in later NestJS versions (6.x and above), where the HTTP context is preserved across all resolver stages by default. If you can upgrade your NestJS version later, you won't need this workaround—but for 5.0.0, this approach should work perfectly.
内容的提问来源于stack exchange,提问作者Tim Lebrun

