javascript - Error on ordering of methods in controller Nestjs - Stack Overflow

I have this basic CRUD methods in Nestjs.The issue I am facing is that when I am applying the getCurre

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/mon';

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

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/mon';

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'
    );
  }
}
Share Improve this question asked Aug 10, 2021 at 5:17 ricksterrickster 3241 gold badge3 silver badges15 bronze badges 5
  • What error do you get? – Daniel Macak Commented Aug 10, 2021 at 5:31
  • [Nest] 7533 - 10/08/2021, 11:04:41 am ERROR [ExceptionsHandler] invalid input syntax for type uuid: "current" QueryFailedError: invalid input syntax for type uuid: "current" this error when I am applying getCurrentUserId() at bottom – rickster Commented Aug 10, 2021 at 5:35
  • Which nestjs version? – Daniel Macak Commented Aug 10, 2021 at 5:54
  • nestjs version : 8.1.1 – rickster Commented Aug 10, 2021 at 5:55
  • I think there something with middleware path issue.. And I am not able to resolve that. – rickster Commented Aug 10, 2021 at 5:56
Add a ment  | 

1 Answer 1

Reset to default 8

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745446126a4628056.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信