Post

[Nest.js 학습일기] typeORM - find, findOne, create, save, delete

[Nest.js 학습일기] typeORM - find, findOne, create, save, delete

레포지토리 주입 과정

이전 학습 과정에서 DB(postsModel)연결까지 진행했다.(https://scorchedrice.github.io/posts/nest-2/)

typeORM으로 post들을 검색 / 등록 / 수정 / 삭제 하는 과정을 진행하려한다.

1. Module에 import 하기

posts.entity.ts에 생성한 레포지토리를 posts.service.ts에서 사용할 수 있도록 posts.module.ts를 수정하는 과정이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// module.ts 일부
@Module({
  imports: [
    TypeOrmModule.forFeature([
      PostsModel,
    ])
  ],
  // forRoot : typeORM을 연결 설정할 때
  // forFeature : model에 해당하는 레포지토리를 주입할 때
  controllers: [PostsController],
  providers: [PostsService],
  // 주입되는 것들로 여기에 등록된 것은 instance를 생성하지 않고 사용 가능
})
export class PostsModule {}

주의할 점은 forFeature()을 사용한다는 것이다.

이렇게 설정을 한다면 service.ts에 레포지토리가 주입할 수 있게 된다.

2. service파일에서 레포지토리 주입하기.

module.ts에서 설정을 마쳤으니 service.ts에서 인식할 수 있도록 해야한다.

1
2
3
4
5
6
7
8
9
@Injectable()
export class PostsService {
  constructor(
    @InjectRepository(PostsModel)
    private readonly postsRepository: Repository<PostsModel>
    // PostsModel을 다루는 레포지토리를 주입하겠다!는 의미
  ) {}
  // 코드들 ..
}

3. find, create, save, delete

주입을 완료했다면 기존에 작성한 로직을 수정하자. 주입이 완료되었으니 this.postRepository ...이런식으로 값을 활용할 수 있다.

1. find , findOne

find()는 모든 값을 찾는다. findOne({where: {조건..})은 조건에 부합하는 것들을 찾는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
async getAllPosts() {
  // typeORM은 모두 async (물론 안해도 되지만 await 쓰고싶을 수 있으니.)
  return this.postsRepository.find();
}

async getPostById(id: number) {
  // id값을 찾아 반환하기.
  const post = await this.postsRepository.findOne(
    {
      where: {
        id,
      }
    }
  );
  if (!post) {
    throw new NotFoundException();
  }
  return post;
}

2. create, save

create로 객체를 생성하고 save로 객체를 저장한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  async createPost(author: string, title: string, content: string) {
    // create => 저장할 객체를 생성한다.
    // save => 객체를 저장한다. (create 매서드에서 생성한 객체로)
    // 이를 조합해서 진행하자!
    const post = this.postsRepository.create({
      author,
      title,
      content,
      likeCount: 0,
      commentCount: 0,
    });
    const newPost = await this.postsRepository.save(post);
    return newPost;
  }

save의 경우 데이터가 존재하는 경우 수정의 역할을, 데이터가 존재하지 않는다면 새로 값을 생성하는 기능을 한다. 따라서 업데이트 또한 save를 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
async updatePost(id: number, author?:string, title?:string, content?:string) {
  // save의 기능
  // 1. 데이터가 존재하지 않으면 (id기준으로) => 새로 생성한다.
  // 2. 만약에 데이터가 존재한다면 => 존재하던 값을 업데이트 한다.
  const post = await this.postsRepository.findOne({
    where: {
      id,
    },
  });
  if (!post) {
    throw new NotFoundException();
  }

  if (author) {
    post.author = author;
  }

  if (title) {
    post.title = title;
  }

  if (content) {
    post.content = content;
  }

  const newPost = await this.postsRepository.save(post);

  return newPost;
}

3. delete

1
2
3
4
5
6
7
8
9
10
11
12
13
  async deletePost(id: number) {
  const post = await this.postsRepository.findOne({
    where: {
      id,
    }
  });
  if (!post) {
    throw new NotFoundException();
  }

  await this.postsRepository.delete(id);
  return id;
}
This post is licensed under CC BY 4.0 by the author.