tkv00 / HOLO

1 stars 4 forks source link

SearchPost Logic #10

Open pjs1710 opened 6 months ago

pjs1710 commented 6 months ago

BackEnd

SearchPostController

package com.backend.Holo.controller;

import com.backend.Holo.entity.SearchPost;
import com.backend.Holo.service.SearchPostService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequiredArgsConstructor
public class SearchPostController {

    private final SearchPostService searchPostService;
    private final RestTemplate restTemplate = new RestTemplate();

    @PostMapping("/search")
    public ResponseEntity<String> searchPosts(@RequestParam String keyword, @RequestParam(defaultValue = "1") int type) {
        List<SearchPost> searchResults = searchPostService.searchPostsByCategory(keyword, type);
        if (searchResults.isEmpty()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("해당 키워드와 카테고리로 검색된 결과가 없습니다.");
        }

        StringBuilder responseBuilder = new StringBuilder();
        for (SearchPost post : searchResults) {
            String url = "http://~:8080/api/post/" + post.getPostId(); // 다른 서버의 IP Address 통신
            try {
                ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
                responseBuilder.append(response.getBody()).append("\n");
            } catch (Exception e) {
                responseBuilder.append("Failed to retrieve post with ID: ").append(post.getPostId()).append("\n");
            }
        }

        return new ResponseEntity<>(responseBuilder.toString(), HttpStatus.OK);
    }
}

// return /postlist 오류가 안나는 테스트용 SearchPostController

//@RestController
//@RequiredArgsConstructor
//public class SearchPostController {
//
//    private final SearchPostService searchPostService;
//
//    @PostMapping("/search")
//    public ResponseEntity<String> searchPosts(@RequestParam String keyword) {
//        List<SearchPost> searchResults = searchPostService.searchPosts(keyword);
//        if (searchResults.isEmpty()) {
//            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("해당 키워드로 검색된 결과가 없습니다.");
//        }
//
//        StringBuilder urlBuilder = new StringBuilder("http://localhost:8080/api/post/?");
//        for (SearchPost post : searchResults) {
//            urlBuilder.append("postId=").append(post.getPostId()).append("&");
//            urlBuilder.append("title=").append(post.getTitle()).append("&");
//        }
//        urlBuilder.setLength(urlBuilder.length() - 1);
//
//        String url = urlBuilder.toString();
//        return ResponseEntity.status(HttpStatus.OK).body("Generated URL: " + url);
//    }
//}
pjs1710 commented 6 months ago

BackEnd

SearchPostEntity

package com.backend.Holo.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;

@Entity
@Getter @Setter
@Table(name = "post")
public class SearchPost {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "postId")
    private Long postId;

    private String title;

    @NotNull
    private Long categoryId;
}
pjs1710 commented 6 months ago

BackEnd

SearchPostRepository

package com.backend.Holo.repository;

import com.backend.Holo.entity.SearchPost;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface SearchPostRepository extends JpaRepository<SearchPost, Long> {

    @Query("SELECT p FROM SearchPost p WHERE p.title LIKE %:keyword%")
    List<SearchPost> findByTitleContaining(@Param("keyword") String keyword);

    @Query("SELECT p FROM SearchPost p WHERE p.title LIKE %:keyword% AND p.categoryId = :categoryId")
    List<SearchPost> findByTitleContainingAndCategoryId(@Param("keyword") String keyword, @Param("categoryId") int categoryId);
}
pjs1710 commented 6 months ago

BackEnd

SearchPostService

package com.backend.Holo.service;

import com.backend.Holo.entity.SearchPost;
import com.backend.Holo.repository.SearchPostRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class SearchPostService {

    private final SearchPostRepository searchPostRepository;

    public List<SearchPost> searchPosts(String keyword) {
        return searchPostRepository.findByTitleContaining(keyword);
    }

    public List<SearchPost> searchPostsByCategory(String keyword, int categoryId) {
        return searchPostRepository.findByTitleContainingAndCategoryId(keyword, categoryId);
    }
}
pjs1710 commented 6 months ago

SearchPost Logic Class들은 추후에 FrontEnd 작업 구체화되면 코드 수정 필요.