TIL 84일차 (20240425)

박세연·2024년 4월 25일

TIL

목록 보기
70/70


오늘 한 일

  • aws s3에 이미지 업로드하기
  • 유저 프로필 조회 시 이미지도 추가, 회원 가입 시 기본 이미지도 같이 등록하기
  • 이미지 리사이징 파이프 추가 with sharp

이미지 리사이징 파이프는 아래 블로그를 참고했다.
출처: https://velog.io/@devhslee02/NestJS-sharp%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EB%A6%AC%EC%82%AC%EC%9D%B4%EC%A7%95


회원 가입 시 기본 이미지 할당은 먼저 s3에 저장되어있는 기본 이미지의 path를 먼저 file에 저장한 후, 해당 file을 유저에 저장하는 식으로 했다.

const imageUrl = process.env.DEFAULT_PROFILE_IMAGE;

    const image = await this.fileRepository.findOneBy({ filePath: imageUrl });

const user = await this.userRepository.save({
      email: createUserDto.email,
      nickname: createUserDto.nickname,
      password: hashedPassword,
      file: image,
    });

아래는 프로필 이미지 변경, 기본 이미지로 변경하는 코드이다.

/* 프로필 이미지 수정 */
  async addImage(user: User, file: Express.Multer.File) {
    const imagename = this.awsService.getUUID();

    const ext = file.originalname.split('.').pop();

    const fileName = `${imagename}.${ext}`;

    const imageUrl = `https://s3.${process.env.AWS_S3_REGION}.amazonaws.com/${process.env.AWS_S3_BUCKET_NAME}/${fileName}`;

    const userId = user.id;

    const newImageUrl = await this.awsService.imageUploadToS3(fileName, file, ext);

    const filePath = await this.fileRepository.save({ filePath: newImageUrl });
    await this.userRepository.update({ id: userId }, { file: filePath });

    return { message: '프로필 이미지 수정 완료' };
  }

// 기본 이미지로 변경

  async defaultImage(user: User) {
    const imageUrl = process.env.DEFAULT_PROFILE_IMAGE;

    const image = await this.fileRepository.findOneBy({ filePath: imageUrl });

    await this.userRepository.update({ id: user.id }, { file: image });

    return { message: '기본 이미지로 변경 완료' };
  }
profile
배워나가는 중

0개의 댓글