//com/example/study/controller/api/UserApiController.java

//...

@Override
@GetMapping("{id}") // /api/user/{id}
public Header<UserApiResponse> read(@PathVariable Long id) {
    log.info("read id : {}", id);
    return userApiLogicService.read(id);
}

@Override
@PutMapping("") // /api/user
public Header<UserApiResponse> update(@RequestBody Header<UserApiReuqest> request) {
    log.info("{}", request);
    return userApiLogicService.update(request);
}

@Override
@DeleteMapping("{id}") // /api/user/{id}
public Header delete(@PathVariable Long id) {
    log.info("delete id : {}", id);
    return userApiLogicService.delete(id);
}
  • read : id로 조회 후 Header<UserApiResponse>로 응답
  • update : Header<UserApiReuqest>로 데이터를 받아 Header<UserApiResponse>로 응답
  • delete : id로 삭제 후 응답할 json body가 없으므로 Header(공통부)로만 응답
//com/example/study/service/UserApiLogicService.java

@Override
public Header<UserApiResponse> read(Long id) {
    return userRepository.findById(id)
        .map(user -> response(user)) //user객체가 있으면 map으로 response 메소드 적용
        .orElseGet( //user가 없다면
            () -> Header.ERROR("데이터 없음")
        );
}

@Override
public Header<UserApiResponse> update(Header<UserApiReuqest> request) {
    UserApiReuqest userApiReuqest = request.getData();
    
    return userRepository.findById(userApiReuqest.getId())
        .map(user -> { //user 객체가 있으면
            //set
            user
                .setAccount(userApiReuqest.getAccount())
                .setPassword(userApiReuqest.getPassword())
                .setStatus(userApiReuqest.getStatus())
                .setPhoneNumber(userApiReuqest.getPhoneNumber())
                .setEmail(userApiReuqest.getEmail())
                .setRegisteredAt(userApiReuqest.getRegisteredAt())
                .setUnregisteredAt(userApiReuqest.getUnregisteredAt());
            return user;
        })
        .map(user -> userRepository.save(user))		//update -> 새로운 user 객체 리턴
        .map(updateUser -> response(updateUser)) 	//userApiResponse
        .orElseGet(() -> Header.ERROR("데이터 없음"));	//위에서 user 객체가 한 번이라도 없을 때
}

@Override
public Header delete(Long id) {
    return userRepository.findById(id)
            .map(user -> {
                userRepository.delete(user);
                return Header.OK();
            })
            .orElseGet(() -> Header.ERROR("데이터 없음"));
}