인생 디벨로퍼

[2단계] Compony Info Update (S3) 본문

Project/Final Project - Sporting (매칭)

[2단계] Compony Info Update (S3)

뫄뫙뫄 2023. 5. 1. 21:12
728x90
반응형

Controller

   @PutMapping("/company/update")
    public ResponseEntity<?> updateCompany(@AuthenticationPrincipal MyUserDetails myUserDetails,
            @RequestBody CompanyRequest.UpdateInDTO updateInDTO) throws IOException {
        CompanyResponse.UpdateOutDTO updateOutDTO = companyService.정보변경(myUserDetails.getUser().getId(),
                updateInDTO);
        return ResponseEntity.ok().body(new ResponseDto<>().data(updateOutDTO));
    }

Service

    @Transactional
    public UpdateOutDTO 정보변경(Long id, UpdateInDTO updateInDTO) throws IOException {

        User userPS = userRepository.findById(id).orElseThrow(() -> {
            throw new Exception400("존재하지 않는 유저입니다.");
        });

        String rawPassword = updateInDTO.getPassword();
        String encPassword = passwordEncoder.encode(rawPassword);

        userPS.setNickname(updateInDTO.getNickname());
        userPS.setPassword(encPassword);
        // userPS.setUpdatedAt(updateInDTO.getUpdatedAt());

        CompanyInfo companyInfoPS = companyInfoRepository.findByUserId(id).orElseThrow(() -> {
            throw new Exception400("존재하지 않는 회사입니다.");
        });
        companyInfoPS.setTel(updateInDTO.getTel());
        companyInfoPS.setBusinessAdress(updateInDTO.getBusinessAdress());
        companyInfoPS.setBusinessNumber(updateInDTO.getBusinessNumber());
        // System.out.println("디버깅 00 : " + companyInfoPS.getFileInfo().getId());
        ProfileFile companyProfileFilePS = profileFileRepository.findById(companyInfoPS.getFileInfo().getId())
                .orElseThrow(() -> {
                    throw new Exception400("Profile File이 존재하지 않습니다.");
                });

        // size가 다르면 false, 같으면 true
        Boolean sizeCheck = S3Utils.updateProfileCheck_Company(companyProfileFilePS,
                updateInDTO.getSourceFile().getFileBase64(), bucket, staticRegion);

        if (!sizeCheck) {
            MultipartFile multipartFile2 = BASE64DecodedMultipartFile
                    .convertBase64ToMultipartFile(updateInDTO.getSourceFile().getFileBase64());

            // 사진이 업데이트 되었을 경우 S3upload 후, DB 반영
            List<String> nameAndUrl = S3Utils.uploadFile(multipartFile2, "CompanyProfile", bucket, amazonS3Client);
            companyProfileFilePS.setFileName(nameAndUrl.get(0));
            companyProfileFilePS.setFileUrl(nameAndUrl.get(1));
        }

        UpdateOutDTO updateOutDTO = new UpdateOutDTO(userPS, companyInfoPS, companyProfileFilePS);

        return updateOutDTO;
    }

user entity 주입

company entity 주입

 

통신

size 가 같으면 완전히 같은 파일이라고 한다@

 

사진정보 주입


DTO

request

package shop.mtcoding.sporting_server.topic.company.dto;

import lombok.*;
import shop.mtcoding.sporting_server.core.enums.field.status.UserStatus;
import shop.mtcoding.sporting_server.modules.company_info.entity.CompanyInfo;
import shop.mtcoding.sporting_server.modules.fileinfo.entity.FileInfo;
import shop.mtcoding.sporting_server.modules.user.entity.User;

import java.time.LocalDateTime;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;

public class CompanyRequest {
    @Getter
    @Setter
    @AllArgsConstructor
    @NoArgsConstructor
    @EqualsAndHashCode
    public static class JoinInDTO {
        @Email(message = "올바른 email 형식이 아닙니다")
        @NotEmpty(message = "email을 입력해주세요")
        private String email;
        @NotEmpty(message = "password를 입력해주세요")
        private String password;
        private String passwordCon;
        private String role;

        public User toEntity() {
            return User.builder()
                    .nickname(email)
                    .password(password)
                    .email(email)
                    .role(role)
                    .status(UserStatus.인증대기)
                    .createdAt(LocalDateTime.now())
                    .build();
        }
    }

    @Getter
    @Setter
    @AllArgsConstructor
    @NoArgsConstructor
    @EqualsAndHashCode
    public static class UpdateInDTO {

        private String nickname;
        private String password;
        private LocalDateTime updatedAt;

        private String tel;
        private String businessAdress;
        private String businessNumber;
        private CompanyFileDTO sourceFile;

        @Getter
        @Setter
        @NoArgsConstructor
        @AllArgsConstructor
        @EqualsAndHashCode
        public static class CompanyFileDTO {
            private Long id;
            private String fileBase64;
        }

    }

}

response

   @Getter
    @Setter
    @NoArgsConstructor
    @EqualsAndHashCode
    public static class UpdateOutDTO {

        private Long id;
        private String nickname;
        private String password;

        private String tel;
        private String businessAdress;
        private String businessNumber;
        private CompanyFileDTO sourceFile = new CompanyFileDTO();

        public UpdateOutDTO(Long id, String nickname, String password, String tel, String businessAdress,
                String businessNumber, CompanyFileDTO companyFile) {
            this.id = id;
            this.nickname = nickname;
            this.password = password;
            this.tel = tel;
            this.businessAdress = businessAdress;
            this.businessNumber = businessNumber;
            this.sourceFile = companyFile;
        }

        public UpdateOutDTO(User userPS, CompanyInfo companyInfoPS, ProfileFile companyProfileFilePS) {
            this.id = userPS.getId();
            this.nickname = userPS.getNickname();
            this.password = userPS.getPassword();
            this.tel = companyInfoPS.getTel();
            this.businessAdress = companyInfoPS.getBusinessAdress();
            this.businessNumber = companyInfoPS.getBusinessNumber();
            this.sourceFile.id = companyProfileFilePS.getId();
            // this.sourceFile.fileName = companyProfileFilePS.getFileName();
            this.sourceFile.fileBase64 = companyProfileFilePS.getFileUrl();
        }

        @Getter
        @Setter
        @NoArgsConstructor
        @AllArgsConstructor
        @EqualsAndHashCode
        public static class CompanyFileDTO {
            private Long id;
            @JsonIgnore
            private String fileName;
            private String fileBase64;

        }

    }

S3 통신

    public static Boolean updateProfileCheck_Company(ProfileFile companyProfileFilePS, String fileBase64, String bucket,
            String staticRegion) throws IOException {

        Boolean check = false;

        AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(staticRegion).build();

        ObjectMetadata objectMetadata = s3Client.getObjectMetadata(bucket,
                companyProfileFilePS.getFileName());

        long companyDBFileSize = objectMetadata.getContentLength();
        MultipartFile multipartFile1 = BASE64DecodedMultipartFile
                .convertBase64ToMultipartFile(fileBase64);
        long companyDTOFileSize = multipartFile1.getSize();
        if (companyDBFileSize == companyDTOFileSize) {
            check = true;
        }

        return check;
    }

 

file_name = 키

file_url = 객체 URL

 

더미에 넣는다.


결과

 

 

728x90
반응형

'Project > Final Project - Sporting (매칭)' 카테고리의 다른 글

Sporting App 정리  (0) 2023.07.02
[2단계] Admin Court 삭제  (0) 2023.05.01
[2단계] Admin court 등록 승인  (0) 2023.05.01
[2단계] Admin page Court view  (0) 2023.05.01
[1단계] Stadium Detail  (0) 2023.05.01