Skip to content
Advertisement

Error on ordering of methods in controller Nestjs

I have this basic CRUD methods in Nestjs. The issue I am facing is that when I am applying the getCurrentUserId() method on top on all methods it works fine but when I am applying in bottom it doesnt work and gives error. Is there anything wrong with middleware ?

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();
    }
  }
}

And I have added the middleware to user.module.ts like this

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

Advertisement

Answer

The route is matching on @Get('/@:userName') before it makes it to @Get('/current') so its executing the code inside of your getUserByUsername method instead.

Just move getCurrentUserId to the top and you should be fine.

Routes are evaluated in the order they are defined and the first matching one is used to handle the request. In general you should always put the most specific routes (the ones without route params) at the top of your controller to avoid this problem.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement