admin管理员组文章数量:1426938
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 applyinggetCurrentUserId()
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
1 Answer
Reset to default 8The 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.
本文标签: javascriptError on ordering of methods in controller NestjsStack Overflow
版权声明:本文标题:javascript - Error on ordering of methods in controller Nestjs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745446125a2658672.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论