본문 바로가기

개발일지

S3 originalName 에러

[Nest] 10780 - 2024. 03. 24. 오후 10:40:20 ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'originalname') TypeError: Cannot read properties of undefined (reading 'originalname')

 

S3를 프로젝트에 적용하던 중 이런 에러를 마주했는데, S3를 프로젝트에 적용해본적이 없고 이번 프로젝트에도 다른 분이 하셔서 어떤 점이 문제인지 알아채기 힘들었다. 조원분들과 대화를 하던 중 파일을 제외한 다른 인자만 수정하면 원래 파일이 없기 때문에 에러를 save 메소드에서 에러를 발생시킨다는 것이다. update.dto에 optional로 처리하니 괜찮아지기에 그 문제인 줄 알았는데, 그게 아니었던 것이다.

 

  async modifyCard(
    user: User,
    cardId: number,
    updateCardDto: UpdateCardDto,
    file: Express.Multer.File,
  ) {
    const card = await this.cardRepository.findOne({
      where: { id: cardId },
    });

    if (!card) {
      throw new NotFoundException('해당하는 카드가 존재하지 않습니다.');
    }

    //이미 입력된 이미지가 있다면 S3에서 기존 이미지 삭제
    if (card.image_url !== null) {
      await this.awsService.DeleteUploadToS3(card.image_url);
    }

    //S3에 이미지 업로드, url return
    const imageName = this.utilsService.getUUID();
    const ext = file.originalname.split('.').pop();

    const imageUrl = await this.awsService.imageUploadToS3(
      `${imageName}.${ext}`,
      file,
      ext,
    );
    
        //DB에 저장
    const uploadCard = await this.cardRepository.save({ ...

 

 

이랬던 코드를

 

  async modifyCard(
    user: User,
    cardId: number, 
    updateCardDto: UpdateCardDto, 
    file?: Express.Multer.File
    ) {
    const card = await this.cardRepository.findOne({
      where: { id: cardId },
    });

    if (!card) {
      throw new NotFoundException('해당하는 카드가 존재하지 않습니다.');
    }

  let imageUrl = card.image_url;

  if (file) {
  //이미 입력된 이미지가 있다면 S3에서 기존 이미지 삭제
  if (card.image_url !== null) {
    await this.awsService.DeleteUploadToS3(card.image_url);
  }
}

  //S3에 이미지 업로드, url return
  const imageName = this.utilsService.getUUID();
  const ext = file? file.originalname.split('.').pop() : null;

  if (ext) {
  imageUrl = await this.awsService.imageUploadToS3(
    `${imageName}.${ext}`,
    file,
    ext,
  );
  }
  

    //DB에 저장
    const uploadCard = await this.cardRepository.save({

 

ext에 file이 없다면 null값을 할당하도록 삼항연산자를 주고 ext가 있을 때만 S3에 이미지를 업로드 하도록 코드를 수정하니 file이 빠진 card 수정도 문제없이 성공했다.