@RestController
@RequiredArgsConstructor
public class MemberApiController {
private final MemberService memberService; // 멤버서비스 = 멤버 도메인의 엔티티를 다루는 장고의 view와 비슷
@PostMapping("/api/v1/members") // api호출 주소
public CreateMemberResponse saveMemberV1(@RequestBody @Valid Member member)
{ // 이렇게하면 json.body내용을 member에 쫙 매핑해준다.
Long id = memberService.join(member);
return new CreateMemberResponse(id);
}
@Data
static class CreateMemberResponse {
private Long id;
public CreateMemberResponse(Long id) {
this.id = id;
}
}
}
외부에서 받아온 json형식을 그대로 사용하는 방식을 버리고 DTO방식 채택해야함
@PostMapping("/api/v2/members")
public CreateMemberResponse saveMemberV2(@RequestBody @Valid CreateMemberRequest request){
Member member = new Member();
member.setName(request.getName());
Long id = memberService.join(member);
return new CreateMemberResponse(id);
}
@Data
static class CreateMemberRequest {
private String name;
}
@PutMapping("/api/v2/members/{id}")
public UpdateMemberResponse updateMemberV2(@PathVariable("id") Long id,
@RequestBody @Valid UpdateMemberRequest request) {
memberService.update(id, request.getName());
Member findMember = memberService.findOne(id);
return new UpdateMemberResponse(findMember.getId(), findMember.getName());
}
@Data
static class UpdateMemberRequest {
private String name;
}
@Data
@AllArgsConstructor
static class UpdateMemberResponse {
private Long id;
private String name;
}
@Transactional
public void update(Long id, String name) {
Member member = memberRepository.findOne(id);
member.setName(name);
}// 멤버서비스에 업데이트 만들어주기
@GetMapping("/api/v1/members")
public List<Member> membersV1() {
return memberService.findMembers();
}
@GetMapping("/api/v2/members")
public Result membersV2() {
List<Member> findMembers = memberService.findMembers(); //엔티티 -> DTO 변환
List<MemberDto> collect = findMembers.stream()
.map(m -> new MemberDto(m.getName()))
.collect(Collectors.toList());// 멤버 리스트를 멤버DTO리스트로 바꿔주는것
return new Result(collect);
}
@Data
@AllArgsConstructor
static class Result<T> {
private T data;
}
@Data
@AllArgsConstructor
static class MemberDto {
private String name;
}
왜냐면 저기서 그냥 콜렉트만 반환하면 json배열로 반환되는데 이것에는 추가로 원하는 값을 넣기가 힘들다
그래서 저렇게 Result로 감싼다음에 멤버로 private int count 이런식으로 추가해서 사용가능하지않을까?
@GetMapping("/api/v2/members")
public Result membersV2() {
List<Member> findMembers = memberService.findMembers(); //엔티티 -> DTO 변환
List<MemberDto> collect = findMembers.stream()
.map(m -> new MemberDto(m.getName()))
.collect(Collectors.toList()); // 멤버 리스트를 멤버DTO리스트로 바꿔주는것
return new Result(collect.size(), collect);
}
@Data
@AllArgsConstructor
static class Result<T> {
private int count;
private T data;
}
@Data
@AllArgsConstructor
static class MemberDto {
private String name;
}
되네~~