DevBoi

[Spring] 좋은 공통화된 Response를 만들어볼까? 본문

Develop/[Spring]

[Spring] 좋은 공통화된 Response를 만들어볼까?

HiSmith 2023. 7. 28. 00:33
반응형

갑자기 생각난것과. 좋은 공통화에 대한 고민을 하다가. 작성하는 글

사실 공통화를 그렇게 열광하지는 않는다.

운영 측면에서 공통화가 무조건 이득이라고 생각하지도 않는다.

때로는 각 상황에 맞는 클래스파일이 하나씩 있는게 좋다고도 생각한다.

 

단순히 아래와 같은 Response가 있다고 가정하자.

 @PostMapping("/sample")
  public Member test(@RequestBody  Member member){
    System.out.println("id_post~~:"+member.getId());
  return member;
  }

 

해당 응답 객체를 좀더 공통화를 한다면

아래와 같을 것이다.

@AllArgsConstructor
@Getter
public class EntityResponse<T> {
  T data;
  String message;
  HttpStatus httpStatus;
}
 @PostMapping("/sample")
  public EntityResponse<Member> test(@RequestBody  Member member){
    System.out.println("id_post~~:"+member.getId());
  return new EntityResponse<Member>(member,"Success", HttpStatus.OK);
  }

 

여기서 와일드 카드 개념으로 제한을 두면 아래와 같을 것이다.

BaseEntity를 상속받는 클래스만 EntityResponse에 넣을 수 있는 것이다.

@Data
@AllArgsConstructor
public class Teacher extends BaseEntity {
  private String name;
  private String id;
  //anti smith!!!!!!!!!!!
}
@Data
@AllArgsConstructor
public class Member extends BaseEntity {
  private String name;
  private String id;
  //anti smith!!!!!!!!!!!
}
@PostMapping("/sample")
  public EntityResponse<Member> test(@RequestBody  Member member){
    System.out.println("id_post~~:"+member.getId());
  return new EntityResponse<>(member,"Success", HttpStatus.OK);
  }
  @PostMapping("/sample2")
  public EntityResponse<Teacher> test2(@RequestBody Teacher teacher){
    return new EntityResponse<>(teacher,"Success", HttpStatus.OK);
  }

 

 

뭔가 구색은 갖춰졌지만 허전하다. count로 데이터 개수를 한번 리턴해보면서 내부 생성자를 생성하고

static으로 각 상황에 맞게 호출하도록 하자

package com.practice.demo.controller;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;

import java.util.Collection;
import java.util.List;


@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class EntityResponse<T> {
  private T data;
  private String message;
  private HttpStatus httpStatus;
  private int count;

  public static <T> EntityResponse<T> successEntityResponse(T data,String message,HttpStatus httpStatus){
    return new EntityResponse<>(data,message,httpStatus);
  }
  private EntityResponse(T data,String message, HttpStatus httpStatus){
    this.data = data;
    this.message = message;
    this.httpStatus = httpStatus;
    if(data instanceof Collection<?>){
      this.count =  ((Collection<?>) data).size();
    }
    else
      this.count = 1;
  }
}
@PostMapping("/sample")
  public EntityResponse<Member> test(@RequestBody  Member member){
    System.out.println("id_post~~:"+member.getId());
    return EntityResponse.successEntityResponse(member,"success",HttpStatus.OK);
  }
  @PostMapping("/sample2")
  public EntityResponse<List<Teacher>> test2(@RequestBody Teacher teacher){
    List<Teacher> teachers = Arrays.asList(teacher,teacher,teacher);
    return EntityResponse.successEntityResponse(teachers,"success",HttpStatus.OK);
  }

 

아래와 같은 Return문을 확인 할 수 있다.

{
    "data": {
        "name": "testUser",
        "id": "cea1e130-64ab-4b7b-8b4f-78a0ffbccbd7"
    },
    "message": "success",
    "httpStatus": "OK",
    "count": 1
}

 

반응형