기존에 Account만 사용하던 것을 AccountDto를 사용해서 return해주는 형식으로 변경하기
@Transactional
public AccountDto createAccount(Long userId, Long initialBalance) {
AccountUser accountUser = accountUserRepository.findById(userId)
.orElseThrow(() -> new AccountException(ErrorCode.USER_NOT_FOUND));
String newAccountNumber = accountRepository.findFirstByOrderByIdDesc()
.map(account -> (Integer.parseInt(account.getAccountNumber())) + 1 + "")
.orElse("10000000000"); // 계죄번호가 하나도 없는 경우 10000000000
return AccountDto.fromEntity(accountRepository.save(
Account.builder()
.accountUser(accountUser)
.accountStatus(IN_USE) // static import
.accountNumber(newAccountNumber)
.registeredAt(LocalDateTime.now())
.build()
)); // entity -> dto로 변환
}
Account 객체를 fromEntitiy라는 static 메서드를 사용해서 AccountDto 객체로 변형한 뒤, return 해준다.
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class AccountDto {
private Long userId;
private String accountNumber;
private Long balance;
private LocalDateTime registeredAt;
private LocalDateTime unregisteredAt;
public static AccountDto fromEntity(Account account){ // AccountDto 생성
return AccountDto.builder()
.userId(account.getId())
.accountNumber(account.getAccountNumber())
.registeredAt(account.getRegisteredAt())
.unregisteredAt(account.getUnRegisteredAt())
.build();
}
}
@PostMapping("/account")
public CreateAccount.Response createAccount(@RequestBody @Valid CreateAccount.Request request) {
return CreateAccount.Response.from(
accountService.createAccount(request.getUserId(), request.getInitialBalance()));
}
Controller에서 CreateAccount.Response 객체로 응답해주기 위해선
accountService.createAccount 메서드로 부터 나오는 AccountDto 객체를 변환해주어야 한다.
public class CreateAccount {
@Getter
@Setter
public static class Request { // inner Class
@NotNull
@Min(1) // 최솟값 : 1부터 시작
private Long userId;
@NotNull
@Min(100) // 최솟값 100원 이상
private Long initialBalance;
}
@Getter
@Setter
@NoArgsConstructor // 매개변수가 없는 생성자
@AllArgsConstructor
@Builder
public static class Response { // inner Class
private Long userId;
private String accountNumber;
private LocalDateTime registeredAt;
public static Response from(AccountDto accountDto){
return Response.builder()
.userId(accountDto.getUserId())
.accountNumber(accountDto.getAccountNumber())
.registeredAt(accountDto.getRegisteredAt())
.build();
}
}
}
CreateAcount에 innerClass Response 내부에 AccountDto로 부터 Response 객체로 변환시켜주는 from 메소드를 만든다.
resources/data.sql
임의로 사용자 데이터를 만들어준다.
만들어주지 않은 경우 계좌 생성 요청을 보낼 때, 에러가 발생한다.
insert into account_user(id, name, created_at, updated_at)
values (1,'Sangyun',now(), now());
insert into account_user(id, name, created_at, updated_at)
values (2,'Sangjun',now(), now());
insert into account_user(id, name, created_at, updated_at)
values (3,'Daeyoung',now(), now());
계좌생성을 위한 POST 요청 보내기(POSTMAN이용)
요청 완료!
'Project' 카테고리의 다른 글
[Toss] 계좌 해제(1) (0) | 2023.08.21 |
---|---|
[Toss] 계좌 생성(4) (0) | 2023.08.21 |
[Toss] 계좌 생성(2) (0) | 2023.08.18 |
[Toss] 계좌 생성(1) (0) | 2023.08.17 |
[Toss] 설계 및 기본 구조 (0) | 2023.08.17 |