如何自定义一个装饰器(如 @CurrentUser)来提取请求上下文信息?需要哪些工具支持?

解读

在国内一线/二线互联网公司的 NestJS 岗位面试中,这道题出现的频率极高。它考察的不仅是“能不能写装饰器”,而是:

  1. 你是否理解 NestJS 的 IoC 与执行上下文(ExecutionContext);
  2. 你是否能把“装饰器 + 守卫/拦截器”组合成可复用的业务抽象;
  3. 你是否知道如何与 Passport、JWT、GraphQL、WebSocket 等不同传输层兼容;
  4. 你是否具备“可测试性”意识——装饰器本身不能依赖全局变量,必须可 mock。

一句话:面试官想看你能不能写出“企业级可落地”的上下文提取方案,而不是 Demo 级玩具。

知识点

  1. TypeScript 装饰器分类:类装饰器、方法装饰器、参数装饰器、属性装饰器;NestJS 中主要用参数装饰器。
  2. NestJS 提供的工厂函数:
    • createParamDecorator:官方推荐,自动注入 ExecutionContext;
    • SetMetadata / Reflector:配合守卫做权限,但不做数据提取;
    • ExecutionContext → host.switchToHttp().getRequest():拿到协议层原始请求。
  3. 请求上下文链路: 请求 → Middleware → Guard → Interceptor → Pipe → Handler → Interceptor → 响应。 装饰器在 Handler 阶段执行,因此只能拿到“之前”附加到请求对象上的数据。
  4. 数据挂载点:
    • REST:req.user(Passport 默认)、req.headers、req.body;
    • GraphQL:GqlExecutionContext.create(host).getContext().req.user;
    • WebSocket:ws 客户端握手阶段把 token 放 query,守卫解析后挂到 client.data.user;
    • gRPC:metadata 中携带 uid,守卫解析后挂到 ctx.user。
  5. 单元测试: 用 @Injectable() 的自定义策略 + ExecutionContext 的 mock 对象,确保装饰器不依赖真实 HTTP 层。

答案

下面给出“企业级可落地”的完整代码,兼容 REST、GraphQL、WebSocket 三种场景,并附带单元测试写法。可直接用于面试白板或机考。

  1. 定义装饰器(src/decorators/current-user.decorator.ts)
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { Socket } from 'socket.io';

export interface JwtPayload {
  userId: string;
  username: string;
}

export const CurrentUser = createParamDecorator(
  (data: keyof JwtPayload | undefined, ctx: ExecutionContext) => {
    const type = context.getType<'http' | 'graphql' | 'ws'>();

    let user: JwtPayload;

    switch (type) {
      case 'http':
        user = ctx.switchToHttp().getRequest().user;
        break;
      case 'graphql':
        const gqlCtx = GqlExecutionContext.create(ctx);
        user = gqlCtx.getContext().req.user;
        break;
      case 'ws':
        const client = ctx.switchToWs().getClient<Socket>();
        user = client.data.user; // 由 WsJwtGuard 提前挂载
        break;
      default:
        throw new Error('Unsupported transport');
    }

    return data ? user?.[data] : user;
  },
);
  1. 在 Guard 中把用户信息挂到正确位置(以 WebSocket 为例)
@Injectable()
export class WsJwtGuard implements CanActivate {
  constructor(private jwtService: JwtService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const client = context.switchToWs().getClient<Socket>();
    const token = client.handshake.query.token as string;
    try {
      const payload = await this.jwtService.verifyAsync<JwtPayload>(token);
      client.data.user = payload; // 关键挂载点
      return true;
    } catch {
      return false;
    }
  }
}
  1. 在 Controller / Resolver / Gateway 中使用
@Controller('order')
export class OrderController {
  @Post()
  create(@Body() dto: CreateOrderDto, @CurrentUser() user: JwtPayload) {
    return this.orderService.create(dto, user.userId);
  }
}

@Resolver()
export class OrderResolver {
  @Mutation(() => Order)
  createOrder(
    @Args('input') dto: CreateOrderDto,
    @CurrentUser() user: JwtPayload,
  ) {
    return this.orderService.create(dto, user.userId);
  }
}

@WebSocketGateway()
export class OrderGateway {
  @UseGuards(WsJwtGuard)
  @SubscribeMessage('order:create')
  handleCreate(
    @MessageBody() dto: CreateOrderDto,
    @CurrentUser('userId') userId: string, // 只取 userId
  ) {
    return this.orderService.create(dto, userId);
  }
}
  1. 单元测试(Jest)
describe('CurrentUser decorator', () => {
  it('should extract full user from http', () => {
    const mockExecutionContext = {
      getType: () => 'http',
      switchToHttp: () => ({
        getRequest: () => ({ user: { userId: 'u1', username: 'tom' } }),
      }),
    } as unknown as ExecutionContext;

    const result = CurrentUser(null, mockExecutionContext);
    expect(result).toEqual({ userId: 'u1', username: 'tom' });
  });

  it('should extract single field', () => {
    const mockExecutionContext = {
      getType: () => 'http',
      switchToHttp: () => ({
        getRequest: () => ({ user: { userId: 'u1', username: 'tom' } }),
      }),
    } as unknown as ExecutionContext;

    const result = CurrentUser('username', mockExecutionContext);
    expect(result).toBe('tom');
  });
});

工具支持清单(国内镜像可稳定下载):

  • @nestjs/core、@nestjs/common:提供 createParamDecorator;
  • @nestjs/graphql:GqlExecutionContext;
  • @nestjs/platform-socket.io:WebSocket 支持;
  • @nestjs/jwt、passport、@nestjs/passport:解析 token;
  • jest:单元测试;
  • ts-node、@nestjs/cli:热重载与构建。

拓展思考

  1. 多租户场景:如果租户 ID 也在 JWT 里,可以扩展 CurrentUser('tenantId'),并在 TypeORM 里用 RequestContextModule 做线程级隔离,避免手动传参。
  2. 性能优化:高并发接口可把用户信息序列化后缓存到 AsyncLocalStorage,减少重复解析 JWT。
  3. 权限细化:把 @CurrentUser() 与 @RequirePermissions('order:create') 组合,守卫里统一做 RBAC,装饰器只负责“拿”,守卫负责“判”,职责清晰。
  4. 微服务链路:在 gRPC 场景下,把 uid 放到 metadata,服务端用 ServerInterceptor 解析后注入 ctx.user,再用同样的 CurrentUser 装饰器提取,实现“跨协议无感知”。
  5. 灰度发布:在装饰器里增加 data === 'grayTag' 分支,直接返回用户标签,供 A/B 策略使用,无需改动业务代码。

掌握以上思路,面试时主动提到“多协议兼容、可测试、可灰度、可扩展”,基本可拿到高分。