Rental Application (React & Spring boot Microservice) - 15 : rental-service(1)

yellow_note·2021년 8월 31일
0

#1 rental-service

rental-service는 post-service에서 대여에 관한 요청이 들어왔을 때 대여를 생성해주는 클래스입니다. 이 외에도 대여 리스트 조회, 대여 상세 조회에 관한 기능도 수행할 수 있죠.

대략적인 시나리오를 보겠습니다.

1) 대여 생성
1-1) 게시글 작성자인 유저-a와 대여 희망자 유저-b는 서로 의견조율을 마치고 대여를 진행하려 합니다.
1-2) 유저-b는 게시글의 '빌릴게요'라는 버튼을 누르고 대여를 진행하면 유저-a에게 대여에 관한 수락 요청이 전송됩니다.
1-3) 유저-a의 수락이 완료되면 대여가 생성됩니다.

2) 대여 리스트 조회
2-1) 유저-a는 자신이 빌려준 대여물품들을 확인하기 위해 마이페이지로 들어갑니다.
2-2) 마이페이지의 대여리스트 탭에 들어가 대여품목들을 확인합니다.

3) 차용 리스트 조회
3-1) 유저-b는 자신이 빌린 차용물품을 확인하기 위해 마이페이지로 들어갑니다.
3-2) 마이페이지의 차용리스트 탭에 들어가 차용품목들을 확인합니다.

2,3 공통) 상세 품목 조회
1) 리스트 탭에서 품목을 클릭하면 상세 품목을 조회할 수 있습니다.

위의 시나리오들을 두고 rental-service를 구현하도록 하겠습니다.

#2 프로젝트 생성


  • pom.xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
  • RentalController
package com.microservices.rentalservice.controller;

import com.microservices.rentalservice.dto.RentalDto;
import com.microservices.rentalservice.service.RentalService;
import com.microservices.rentalservice.vo.RequestCreate;
import com.microservices.rentalservice.vo.ResponseRental;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/")
public class RentalController {
    private RentalService rentalService;
    private Environment env;

    @Autowired
    public RentalController(
        RentalService rentalService,
        Environment env
    ) {
        this.rentalService = rentalService;
        this.env = env;
    }

    @GetMapping("/health_check")
    public String status() {
        return String.format(
            "It's working in Post Service"
                + ", port(local.server.port) =" + env.getProperty("local.server.port")
                + ", port(server.port) =" + env.getProperty("server.port")
        );
    }

    @PostMapping("/create")
    public ResponseEntity<?> createRental(@RequestBody RequestCreate rentalVo) {
        log.info("Rental Service's Controller Layer :: Call createRental Method!");

        RentalDto rentalDto = RentalDto.builder()
                                       .postId(rentalVo.getPostId())
                                       .price(rentalVo.getPrice())
                                       .owner(rentalVo.getOwner())
                                       .borrower(rentalVo.getBorrower())
                                       .startDate(rentalVo.getStartDate())
                                       .endDate(rentalVo.getEndDate())
                                       .build();

        RentalDto rental = rentalService.createRental(rentalDto);
        ResponseRental responseRental = ResponseRental.builder()
                                                      .rentalId(rental.getRentalId())
                                                      .postId(rentalVo.getPostId())
                                                      .price(rentalVo.getPrice())
                                                      .owner(rentalVo.getOwner())
                                                      .borrower(rentalVo.getBorrower())
                                                      .startDate(rentalVo.getStartDate())
                                                      .endDate(rentalVo.getEndDate())
                                                      .createdAt(rental.getCreatedAt())
                                                      .build();

        return ResponseEntity.status(HttpStatus.CREATED).body(responseRental);
    }

    @GetMapping("/{rentalId}/rental")
    public ResponseEntity<?> getRentalByRentalId(@PathVariable("rentalId") String rentalId) {
        log.info("Rental Service's Controller Layer :: Call getRentalByRentalId Method!");

        RentalDto rentalDto = rentalService.getRentalByRentalId(rentalId);

        return ResponseEntity.status(HttpStatus.OK).body(ResponseRental.builder()
                                                                       .rentalId(rentalDto.getRentalId())
                                                                       .postId(rentalDto.getPostId())
                                                                       .price(rentalDto.getPrice())
                                                                       .owner(rentalDto.getOwner())
                                                                       .borrower(rentalDto.getBorrower())
                                                                       .startDate(rentalDto.getStartDate())
                                                                       .endDate(rentalDto.getEndDate())
                                                                       .createdAt(rentalDto.getCreatedAt())
                                                                       .build());
    }

    @GetMapping("/{owner}/my_rentals")
    public ResponseEntity<?> getRentalsByOwner(@PathVariable("owner") String owner) {
        log.info("Rental Service's Controller Layer :: Call getMyRentalByUserId Method!");

        Iterable<RentalDto> rentalList = rentalService.getRentalsByOwner(owner);
        List<ResponseRental> result = new ArrayList<>();

        rentalList.forEach(v -> {
            result.add(ResponseRental.builder()
                                     .rentalId(v.getRentalId())
                                     .postId(v.getPostId())
                                     .price(v.getPrice())
                                     .owner(v.getOwner())
                                     .borrower(v.getBorrower())
                                     .startDate(v.getStartDate())
                                     .endDate(v.getEndDate())
                                     .createdAt(v.getCreatedAt())
                                     .build());
        });

        return ResponseEntity.status(HttpStatus.OK).body(result);
    }

    @GetMapping("/{borrower}/borrow_rentals")
    public ResponseEntity<?> getRentalsByBorrower(@PathVariable("borrower") String borrower) {
        log.info("Rental Service's Controller Layer :: Call getBorrowRentalByUserId Method!");

        Iterable<RentalDto> rentalList = rentalService.getRentalsByBorrower(borrower);
        List<ResponseRental> result = new ArrayList<>();

        rentalList.forEach(v -> {
            result.add(ResponseRental.builder()
                                     .rentalId(v.getRentalId())
                                     .postId(v.getPostId())
                                     .price(v.getPrice())
                                     .owner(v.getOwner())
                                     .borrower(v.getBorrower())
                                     .startDate(v.getStartDate())
                                     .endDate(v.getEndDate())
                                     .createdAt(v.getCreatedAt())
                                     .build());
        });

        return ResponseEntity.status(HttpStatus.OK).body(result);
    }

    @DeleteMapping("/{rentalId}/cancel")
    public ResponseEntity<?> deleteRental(@PathVariable("rentalId") String rentalId) {
        log.info("Rental Service's Controller Layer :: Call deleteRental Method!");

        RentalDto rentalDto = rentalService.deleteRental(rentalId);

        ResponseRental responseRental = ResponseRental.builder()
            .rentalId(rentalDto.getRentalId())
            .build();

        return ResponseEntity.status(HttpStatus.OK).body(responseRental.getRentalId() + " :: Successfully delete");
    }
}

컨트롤러 부분을 작성한 후 오류 코드들을 고쳐나가는 방식으로 진행하겠습니다. 그리고 vo, dto, entity 클래스들을 만들도록 하겠습니다.

  • RentalEntity
package com.microservices.rentalservice.entity;

import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Data
@Entity
@Table(name="rentals")
@NoArgsConstructor
public class RentalEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String rentalId;

    @Column(nullable = false)
    private Long postId;

    @Column(nullable = false)
    private Long price;

    @Column(nullable = false)
    private String owner;

    @Column(nullable = false)
    private String borrower;

    @Column(nullable = false)
    private String startDate;

    @Column(nullable = false)
    private String endDate;

    @Column(nullable = false)
    private String createdAt;

    @Builder
    public RentalEntity(
        String rentalId,
        Long postId,
        Long price,
        String owner,
        String borrower,
        String startDate,
        String endDate,
        String createdAt
    ) {
        this.rentalId = rentalId;
        this.postId = postId;
        this.price = price;
        this.owner = owner;
        this.borrower = borrower;
        this.startDate = startDate;
        this.endDate = endDate;
        this.createdAt = createdAt;
    }
}
  • vo.RequestCreate
package com.microservices.rentalservice.vo;

import lombok.Getter;

import javax.validation.constraints.NotNull;

@Getter
public class RequestCreate {
    @NotNull(message="PostId cannot be null")
    private Long postId;

    @NotNull(message="Price cannot be null")
    private Long price;

    @NotNull(message="Owner cannot be null")
    private String owner;

    @NotNull(message="Borrower cannot be null")
    private String borrower;

    @NotNull(message="StartDate cannot be null")
    private String startDate;

    @NotNull(message="EndDate cannot be null")
    private String endDate;
}
  • ResponseRental
package com.microservices.rentalservice.vo;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseRental {
    private String rentalId;
    private Long postId;
    private Long price;
    private String owner;
    private String borrower;
    private String startDate;
    private String endDate;
    private String createdAt;

    @Builder
    public ResponseRental(
        String rentalId,
        Long postId,
        Long price,
        String owner,
        String borrower,
        String startDate,
        String endDate,
        String createdAt
    ) {
        this.rentalId = rentalId;
        this.postId = postId;
        this.price = price;
        this.owner = owner;
        this.borrower = borrower;
        this.startDate = startDate;
        this.endDate = endDate;
        this.createdAt = createdAt;
    }
}
  • RentalDto
package com.microservices.rentalservice.dto;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RentalDto {
    private String rentalId;
    private Long postId;
    private Long price;
    private String owner;
    private String borrower;
    private String startDate;
    private String endDate;
    private String createdAt;

    @Builder
    public RentalDto(
        String rentalId,
        Long postId,
        Long price,
        String owner,
        String borrower,
        String startDate,
        String endDate,
        String createdAt
    ) {
        this.rentalId = rentalId;
        this.postId = postId;
        this.price = price;
        this.owner = owner;
        this.borrower = borrower;
        this.startDate = startDate;
        this.endDate = endDate;
        this.createdAt = createdAt;
    }
}

여기까지 컨트롤러부터 dto클래스의 구현을 마치고 다음 포스트에서는 서비스, 레포지토리, 카프카에 대해 살펴 보도록 하겠습니다.

0개의 댓글

관련 채용 정보