Skip to content

Commit

Permalink
feat: add search feature
Browse files Browse the repository at this point in the history
  • Loading branch information
sspzoa committed Nov 7, 2024
1 parent e4c60b0 commit a92d8cd
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 1 deletion.
3 changes: 2 additions & 1 deletion app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from app.dependencies.auth import verify_token
from app.routes import ping, root
from app.routes.preference import preference
from app.routes.recipe import recipe, ingredient_info, cooking_step, chat
from app.routes.recipe import recipe, ingredient_info, cooking_step, chat, search
from app.routes.refrigerator import ingredient_detect, refrigerator
from app.routes.refrigerator import rearrange_refrigerator

Expand Down Expand Up @@ -35,6 +35,7 @@
app.include_router(ingredient_info.router, dependencies=[Depends(verify_token)])
app.include_router(cooking_step.router, dependencies=[Depends(verify_token)])
app.include_router(chat.router, dependencies=[Depends(verify_token)])
app.include_router(search.router, dependencies=[Depends(verify_token)])
app.include_router(ingredient_detect.router, dependencies=[Depends(verify_token)])
app.include_router(refrigerator.router, dependencies=[Depends(verify_token)])
app.include_router(rearrange_refrigerator.router, dependencies=[Depends(verify_token)])
Expand Down
17 changes: 17 additions & 0 deletions app/models/recipe/search_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from typing import List

from pydantic import BaseModel


class SearchRequest(BaseModel):
search_query: str


class RecipeSimple(BaseModel):
id: str
name: str
image_url: str


class SearchResponse(BaseModel):
search_results: List[RecipeSimple]
52 changes: 52 additions & 0 deletions app/routes/recipe/search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from bson.regex import Regex
from fastapi import APIRouter, HTTPException
from pymongo import ASCENDING

from app.database import recipe_collection
from app.models.recipe.search_models import SearchResponse, RecipeSimple

router = APIRouter()


@router.get("/recipe/search", tags=["Recipe"], response_model=SearchResponse)
async def search_recipes(query: str):
"""
주어진 검색어로 레시피를 검색합니다.
검색은 레시피 이름과 설명을 대상으로 수행됩니다.
Args:
query (str): 검색할 키워드
Returns:
SearchResponse: 검색 결과 목록
"""
try:
# 검색어가 비어있는 경우 처리
if not query.strip():
raise HTTPException(status_code=400, detail="검색어를 입력해주세요.")

# 대소문자 구분 없이 검색하기 위한 정규식 패턴 생성
search_pattern = Regex(f".*{query}.*", "i")

# 이름 또는 설명에 검색어가 포함된 레시피 검색
search_results = await recipe_collection.find({
"$or": [
{"name": search_pattern},
{"description": search_pattern}
]
}).sort("name", ASCENDING).to_list(length=None)

# 검색 결과를 RecipeSimple 모델로 변환
simple_results = [
RecipeSimple(
id=str(recipe["_id"]),
name=recipe["name"],
image_url=recipe.get("image_base64", "") # Base64 이미지 URL 사용
)
for recipe in search_results
]

return SearchResponse(search_results=simple_results)

except Exception as e:
raise HTTPException(status_code=500, detail=f"검색 중 오류가 발생했습니다: {str(e)}")

0 comments on commit a92d8cd

Please sign in to comment.