Controller, Service, Repository

ON&OFF·2024년 6월 20일
0

1. Controller

  • 클라이언트와 닿아있는 구역
  • 실제 구현해야 할 API 함수 틀을 작성한다.
  • 여기선 실제 구현이 아니라 데이터를 주고받고 하는 활동만 진행됨
  • 컨트롤러에서 서비스에게 클라이언트에서 이러이러한 게 필요하다 라고 요청하면, 서비스는 레포지토리에 접근하던 안하던 해서 함수를 구현후 컨트롤러에게 건네준다
    • 날씨 일기 어플에선 다음과 같은 예시를 들 수 있다.

      @Controller
      public class DiaryController {
      
      	private final DiaryService diaryService;
       
       public DiaryController (DiatyService diaryService) {
       	this.diaryService = diaryService;
           }
           
       @PostMapping("/create/diary")
       void createDiary(@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date, @RequestBody String text) {
       	diaryService.createDiary()
           }
          } // 날짜와 일기 내용을 파라미터로 받는 함수
          
          @GetMapping("/read/diary")
          List<Diary> readDiary(@RequestParam @DateTimeFormat(iso = DatetimeFormat.ISO.DATE) LocalDate date) {
          return diaryService.readDiary(date); 
          // 날짜에 대한 일기를 가져오는 함수
          
      
      

2. Service

  • 컨트롤러와 레포지토리를 연결하는 구역
  • 날씨 일기 어플에선 데이터를 가져오고/가져온 데이터 파싱하고/파싱된 데이터와 일기를 db에 넣기 까지의 기능이 구현됨
  • 핵심 api 기능들이 실제로 구현되는 곳
@Service
public class DiaryService {

	@Value("${openweathermap.key}")
    private String apiKey;

	public void createDiary(LocalDate date, String text) {
    	String weatherData = getWeatherString(); // 날씨 데이터 가져왔음
        // 받아온 날씨 JSON 파싱하기
        Map<String, Object> parsedWeather = parseWaether(weatherData);
        
        // 파싱된 데이터 + 일기 값 우리 DB에 넣기
    
    
    private String getWeatherString() { // openmap 에서 날씨 데이터 가져오는 함수
    	String apiUrl="https://api.openweathermap.org/ + apiKey;
        
    try {
  	  URL url = new URL(apiUrl);
   		 HttpURLConnection connection = (HttpURLConnection) url.openConnectrion();
         connection.setRequestMethod("GET");
         int reponseCode = connection.getReponseCode();
         BufferedReader br;
         if (reponseCode == 200) {
         	br = new BufferEader (new InputStreamReader(connection.getInputStream()));
         } else {
         		br = new BufferEader (new InputStreamReader(connection.getErrorStream()));
                }
            String inputLine;
            StringBuilder response = new StringBuilder();
            while((inputLine = br.readLine()) != null) {
            response.appned(inputLine);
            }
            br.close();
         	
         return response.toString();
    
    } catch (Exception e) {
    return "failed to get response";
    }
    
    public void readDiary(LocalDate date) {
    diaryRepository.findAllByDate(date);

3. Repository

  • DB 테이블과 연결할 객체를 구성한다.
  • 테이블에서 데이터를 가져오거나 넣거나 할때 이 함수에 작성한다.

@Repository
public interface DiaryRepository extends JpaRepository<Diary, Integer> {
	List<DIary> findAllByDate(LocalDate date);
    // 데이트를 가지고 그날의 전체 일기를 가져오는 함수
    
    List<Diary> findAllByDateBetween(LocalDate startDate, Localdate endDate);
profile
안 되면 될 때까지

0개의 댓글