TypeORM 함수 with NestJS

2023. 12. 14. 11:53ORM/TypeORM

 

@Injectable()
export class PostsService {
  constructor(
    @InjectRepository(PostsModel)
    private readonly postsRepository: Repository<PostsModel>,
  ) {}
  
  //...

}

 

find

다수의 데이터 가져오기

  async getAllPosts() {
    return this.postsRepository.find();
  }

 

findOne

하나의 데이터 찾기

 

  async getPostById(id: number) {
    const post = await this.postsRepository.findOne({
      where: {
        id,
      },
    });

    if (!post) {
      throw new NotFoundException();
    }

    return post;
  }

 

create

데이터 생성하기

 

  async createPost(author: string, title: string, content: string) {
    // 1) create -> 저장할 객체를 생성한다.
    // 2) save -> 객체를 저장한다. (create 메서드에서 생성한 객체로)

    const post = this.postsRepository.create({
      author,
      title,
      content,
      likeCount: 0,
      commentCount: 0,
    });

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

    return newPost;
  }

 

 

save

데이터 업데이트하기

 

async updatePost(id: number, author: string, title: string, content: string) {
    // save 의 기능
    // 1) 만약 데이터가 존재하지 않는다면 (id 기준으로) 새로 생성한다.
    // 2) 만약 데이터가 존재한다면 (같은 id의 값이 존재한다면) 존재하던 값을 업데이트 한다.

    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;
  }

 

delete

삭제하기

 

  async deletePost(id: number) {
    const post = await this.postsRepository.findOne({
      where: {
        id,
      },
    });
    if (!post) {
      throw new NotFoundException();
    }

    await this.postsRepository.delete(id);

    return id;
  }

 

'ORM > TypeORM' 카테고리의 다른 글

Type ORM 알아보기 [NestJS]  (0) 2023.12.15