@Controller('posts')
export class PostsController {
constructor(private readonly postsService: PostsService) {}
이전에 Service에 있는 것을 주입하여 Controller 에서 사용하도록 하는 것을 기억할 것이다.
마찬가지로 우리가 만든 Entity를 사용할 수 있도록 Service에 주입하도록 하는데, Repository라는 클래스를 주입한다.
Repository는 생성한 Entity를 사용할 수 있도록 하는 연결다리 클래스라고 생각하면 된다.
Repository를 주입할 Entity 등록
import { Module } from '@nestjs/common';
import { PostsService } from './posts.service';
import { PostsController } from './posts.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PostsModel } from './entities/posts.entity';
@Module({
imports: [TypeOrmModule.forFeature([PostsModel])],
controllers: [PostsController],
providers: [PostsService],
})
export class PostsModule {}
imports: [TypeOrmModule.forFeature([PostsModel])],
Entity를 주입해서 사용하기 위해선 우선 등록을 해야한다. 해당되는 module.ts에 @Module안에 imports 한다.
TypeOrmModule.forFeature([Entity, ...]) 안에 작성해야 한다.
Repository 주입하기
@Injectable()
export class PostsService {
constructor(
@InjectRepository(PostsModel)
private readonly postsRepository: Repository<PostsModel>,
) {}
생성자 안에 위와 같이 작성하여 주입한다.
사용하기
async getAllPosts() {
return this.postsRepository.find();
}
이후 Repository를 사용할 수 있게 된다.
'NestJS' 카테고리의 다른 글
Entity Embedding VS Table Inheritance (0) | 2025.02.24 |
---|---|
TypeORM - Entity Column 탐구 (0) | 2025.02.24 |
TypeORM - Entity로 테이블 생성하기 (0) | 2025.02.24 |
TypeORM - NestJS에 설정하기 (0) | 2025.02.24 |
VCS에서 PostgreSQL 툴 사용하기 (0) | 2025.02.24 |