JS/Nest.js
[Nest] DI 실습 export service, import module, Nest can't resolve dependencies of the 해결, 게시글 생성제한 구현
Mini_96
2024. 9. 20. 16:52
* 문제
- 현재 post 에서 아래와같은 가드를 사용하려고 한다.
- authService, usersService를 주입받아야 사용가능하다.
@Injectable()
export class BearerTokenGuard implements CanActivate {
constructor(private readonly authService: AuthService,
private readonly usersService : UsersService) {} //런타임에서 DI에서 주입해줌
* 해결 (Nest can't resolve dependencies of the 해결)
- 가드가 속한, auth 모듈에서 service를 export 해준다.
@Module({
imports:[
JwtModule.register({}),
UsersModule,
],
controllers: [AuthController],
providers: [AuthService],
exports: [AuthService],
})
export class AuthModule {}
- post module에서 authmodule을 import 해준다.
@Module({
imports:[
TypeOrmModule.forFeature([
PostsModel
]),
AuthModule,
UsersModule,
],
controllers: [PostsController],
providers: [PostsService],
})
export class PostsModule {}
- 그러면, import할때도 service만 import하면 되는거 아닌가?
- 어노테이션이 붙은 클래스는 모듈 단위로 import해야한다고 한다!!
* 게시글 생성제한 구현
- 기존코드 문제
- authorId만 알면 url으로 다른사람의 게시글 등록 가능
@Post()
createPost(@Body() postData: { authorId: number; title: string; content:string; }){
return this.postsService.createPost(postData.authorId, postData.title, postData.content);
- 해결
- 앞에 AccessTokenGuard를 둬서 AccessToken을 확인한후에 입장시키도록 수정
- id를 Body에 받아오는대신, req에 넣어놓은 user 정보 사용
@Post()
@UseGuards(AccessTokenGuard)
createPost(
@Request() req : any,
@Body('title') title: string,
@Body('content') content:string, ){
return this.postsService.createPost(req.user.id , title, content);
}