💻/프로젝트

컬렉션 컨텐츠 추가 기능 구현

S0 2024. 4. 11. 23:52

 

// collection.controller.ts


// 컨텐츠 추가
  @UseGuards(AuthGuard('jwt'))
  @Post('/:collectionId/content')
  async addContentToCollection(
    @UserInfo() user: Users,
    @Param('collectionId') collectionId: number,
    @Body('webContentId') webContentId: number,
  ) {
    const userId = user.id;

    const isContentExist =
      await this.collectionService.isContentExistInCollection(
        userId,
        collectionId,
        webContentId,
      );
    if (isContentExist) {
      throw new BadRequestException('이미 존재하는 컨텐츠입니다.');
    }

    return await this.collectionService.addContentToCollection(
      userId,
      collectionId,
      webContentId,
    );
  }

  // 컨텐츠 삭제
  @UseGuards(AuthGuard('jwt'))
  @Delete('/:collectionId/content')
  async removeContentFromCollection(
    @UserInfo() user: Users,
    @Param('collectionId') collectionId: number,
    @Body('webContentId') webContentId: number,
  ) {
    const userId = user.id;
    return await this.collectionService.removeContentFromCollection(
      userId,
      collectionId,
      webContentId,
    );
  }
  // collection.service.ts
  
  
  // 컨텐츠 추가
  async addContentToCollection(
    userId: number,
    collectionId: number,
    webContentId: number,
  ): Promise<void> {
    const collection = await this.colRepository.findOne({
      where: { id: collectionId },
    });
    if (!collection) {
      throw new NotFoundException('컬렉션이 존재하지 않습니다.');
    }

    if (collection.userId !== userId) {
      throw new ForbiddenException('내 컬렉션에만 컨텐츠 추가가 가능합니다.');
    }

    const webContent = await this.webContentRepository.findOne({
      where: { id: webContentId },
    });
    if (!webContent) {
      throw new NotFoundException('작품이 존재하지 않습니다.');
    }

    const contentCollection = new ContentCollection();
    contentCollection.collection = collection;
    contentCollection.webContent = webContent;
    await this.contentCollectionRepository.save(contentCollection);
  }

  async isContentExistInCollection(
    userId: number,
    collectionId: number,
    contentId: number,
  ): Promise<boolean> {
    const contentCollection = await this.contentCollectionRepository.findOne({
      where: {
        collection: { id: collectionId },
        webContent: { id: contentId },
      },
      relations: ['collection', 'webContent'],
    });
    return !!contentCollection;
  }

  // 컨텐츠 삭제
  async removeContentFromCollection(
    userId: number,
    collectionId: number,
    webContentId: number,
  ): Promise<void> {
    const collection = await this.colRepository.findOne({
      where: { id: collectionId },
    });

    if (collection.userId !== userId) {
      throw new ForbiddenException('내 컬렉션에서만 컨텐츠 삭제가 가능합니다.');
    }

    const contentCollection = await this.contentCollectionRepository.findOne({
      where: {
        collection: { id: collectionId },
        webContent: { id: webContentId },
      },
    });

    if (!contentCollection) {
      throw new NotFoundException('컨텐츠가 컬렉션에 존재하지 않습니다.');
    }

    await this.contentCollectionRepository.remove(contentCollection);
  }

기존에 구현한 컬렉션 기능에 데이터 스크래핑을 통해 가져온 웹소설, 웹툰 데이터를 추가하는 로직이다.

컬렉션 상세 조회 시 작품 데이터도 함께 보이도록 기존 코드를 수정했고, 그외에는 나의 컬렉션에만 컨텐츠 추가가 가능하도록 하고 컨텐츠 중복 등록을 막는 부분을 신경써서 작성했다.

테스트까지 끝나긴 했는데 메서드 이름이 너무 길어서 간결하고 명확한 이름을 고민중이다.

'💻 > 프로젝트' 카테고리의 다른 글

오류 해결 정리  (0) 2024.04.17
프로젝트 컬렉션 기능 문제 해결  (0) 2024.04.16
프로젝트 최종 엔티티  (0) 2024.04.08
최종 프로젝트 트러블 슈팅  (0) 2024.04.04
컬렉션 북마크 기능 고민  (0) 2024.04.03