控制器Nestjs中的方法排序错误

2022-03-04 00:00:00 javascript nestjs

我在Nestjs中有这个基本的CRUD方法。 我面临的问题是,当我在所有方法上面应用getCurrentUserId()方法时,它工作得很好,但当我在下面应用时,它就不能工作,并且会出现错误。 中间件有什么问题吗?

user.controller.ts

@Controller('users')
@Serialize(UserDto)
export class UsersController {
  constructor(private usersService: UsersService) {}

  @Post('/signup')
  create(@Body() createUserDto: CreateUserDto): Promise<User> {
    return this.usersService.create(createUserDto);
  }

  @Get('/@:userName')
  async getUserByUsername(@Param('userName') userName: string) {
    const user = await this.usersService.findByName(userName);
    console.log(userName);
    if (!user) {
      throw new NotFoundException('User Not Found');
    }

    return user;
  }

  //! Testing for current user
  @Get('/current')
  @UseGuards(JwtAuthGuard)
  async getCurrentUserId(@CurrentUser() id: string) {
    console.log('running endpoint');
    return id;
  }
}

current-user.decorator.ts

import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const CurrentUser = createParamDecorator(
  (data : unknown , context : ExecutionContext) => {
    const req = context.switchToHttp().getRequest();
    console.log("I am running")
    return req.id;
  }
)

current-user.middleware.ts

@Injectable()
export class CurrentUserMiddleware implements NestMiddleware {
  constructor(private usersService: UsersService) {}

  async use(req: RequestId, res: Response, next: NextFunction) {
    const token = req.headers['authorization'];
    console.log(token);
    if (!token) {
      throw new UnauthorizedException('Unauthorized');
    }
    try {
      const { userId } =
        await this.usersService.getUserByToken(token);
      req.id = userId;
      console.log(req.id)
      next();
    } catch {
      throw new UnauthorizedException();
    }
  }
}

我已经将中间件添加到user.module.ts,如下所示

export class UsersModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(CurrentUserMiddleware).forRoutes(
      'users/current'
    );
  }
}

解决方案

路由在到达@Get('/current')之前在@Get('/@:userName')上匹配,因此它改为执行getUserByUsername方法内部的代码。

只需将getCurrentUserId移到顶部,就可以了。

路由按照定义的顺序进行评估,第一个匹配的路由用于处理请求。通常,您应该始终将最具体的路由(没有路由参数的路由)放在控制器的顶部,以避免此问题。

相关文章