Skip to Content
BackendNestJs16-Custom Decorator

1. AccessTokenGuard 적용

post 작성은 로그인을 해야지만, 작성할 수 있게 바꿔보겠다.

posts.controller.ts
1
// posts.controller.ts 생략
2
@Post()
3
@UseGuards(AccessTokenGuard)
4
postPosts(
5
@Request() req: any,
6
@Body('title') title: string, //
7
@Body('content') content: string,
8
// 기본값을 true로 설정하는 파이프
9
// @Body('isPublic', new DefaultValuePipe(true)) isPublic: boolean,
10
) {
11
const authorId = req.user.id
12
return this.postsService.createPost(authorId, title, content)
13
}
  • 로그인한 사용자만 포스트작성 API를 사용할 수 있게 바꾸려면,
  • AccessTokenGuard을 적용해주면 된다.
  • cf. 이를 private route라고 부른다.

그러면 아래와 같이 디펜던시 에러가 나올 것이다.

txt
1
Nest can't resolve dependencies of the AccessTokenGuard
2
(?, UsersService). Please make sure that the argument AuthService
3
at index [0] is available in the PostsModule context.

posts 모듈에 AuthService, UsersService와 JwtModule.register(), UsersModel까지 추가해준다.

posts.module.ts
1
// posts.module.ts 생략
2
@Module({
3
imports: [
4
JwtModule.register({}), // 추가
5
TypeOrmModule.forFeature([PostsModel, UsersModel]), // 추가
6
],
7
controllers: [PostsController],
8
providers: [PostsService, AuthService, UsersService], // 추가
9
})
10
export class PostsModule {}

2. User 커스텀 데코레이터 생성

모든 데코레이터는 대문자로 시작한다.

users/decorator/user.decorator.ts 파일을 만든다.

users/decorator/user.decorator.ts
1
import { ExecutionContext, InternalServerErrorException, createParamDecorator } from '@nestjs/common'
2
3
export const User = createParamDecorator((data, context: ExecutionContext) => {
4
const req = context.switchToHttp().getRequest()
5
const user = req.user
6
7
if (!user) {
8
throw new InternalServerErrorException(
9
'User 데코레이터는 AccessTokenGuard와 함께 사용해야 합니다. Request에 user 프로퍼티가 존재하지 않습니다!',
10
)
11
}
12
13
return user
14
})

posts 컨트롤러에 User 커스텀 데코레이터를 적용한다.

posts.controller.ts
1
// posts.controller.ts 생략
2
@Post()
3
@UseGuards(AccessTokenGuard)
4
postPosts(
5
@User() user: UsersModel, // ✅ User 커스텀 데코레이터를 적용
6
@Body('title') title: string,
7
@Body('content') content: string,
8
// 기본값을 true로 설정하는 파이프
9
// @Body('isPublic', new DefaultValuePipe(true)) isPublic: boolean,
10
) {
11
return this.postsService.createPost(user.id, title, content)
12
}

auth 서비스에 토큰 검증에 try~catch 문을 적용한다.

auth.service.ts
1
// auth.service.ts 생략
2
/*** 토큰 검증
3
*
4
*/
5
verifyToken(token: string) {
6
try {
7
return this.jwtService.verify(token, {
8
secret: JWT_SECRET,
9
})
10
} catch (err) {
11
throw new UnauthorizedException('토큰이 만료됏거나 잘못된 토큰입니다.')
12
}
13
}

포스트맨에서 authorId 없이, 토큰에서 유저 정보를 꺼내 포스트를 생성하는 걸 확인한다.


3. 커스텀 데코레이터의 data 파라미터 사용

data 파라미터를 사용해서, 사용자의 특정 파라미터를 넣어주면, 해댱되는 프로퍼티를 반환하게 해줄 수 있다.

users/decorator/user.decorator.ts
1
import { ExecutionContext, InternalServerErrorException, createParamDecorator } from '@nestjs/common'
2
import { UsersModel } from '../entities/users.entity'
3
4
export const User = createParamDecorator(
5
(
6
data: keyof UsersModel | undefined, //
7
context: ExecutionContext,
8
) => {
9
const req = context.switchToHttp().getRequest()
10
const user = req.user as UsersModel
11
12
if (!user) {
13
throw new InternalServerErrorException(
14
'User 데코레이터는 AccessTokenGuard와 함께 사용해야 합니다. Request에 user 프로퍼티가 존재하지 않습니다!',
15
)
16
}
17
18
if (data) {
19
return user[data]
20
}
21
22
return user
23
},
24
)

posts 컨트롤러에 User 커스텀 데코레이터를 적용한다.

posts.controller.ts
1
// posts.controller.ts 생략
2
@Post()
3
@UseGuards(AccessTokenGuard)
4
postPosts(
5
@User('id') userId: number, // ✅ data 파라미터를 이용해 특정 파라미터만 받을 수 있다.
6
@Body('title') title: string, //
7
@Body('content') content: string,
8
// 기본값을 true로 설정하는 파이프
9
// @Body('isPublic', new DefaultValuePipe(true)) isPublic: boolean,
10
) {
11
return this.postsService.createPost(userId, title, content)
12
}