1- from fastapi import APIRouter , Request , status
1+ from fastapi import APIRouter , HTTPException , Request , status
22from pydantic import BaseModel
33
44from app .schemas import Library as LibrarySchema
5- from app .services .database .models .libraries import Library
6- from app .services .database .orm .library import insert_library
5+ from app .schemas import Subscription as SubscriptionSchema
6+ from app .services .database .models import Library , Subscription
7+ from app .services .database .orm .library import (
8+ get_library_ids_by_multiple_names ,
9+ insert_library ,
10+ )
11+ from app .services .database .orm .subscription import upsert_multiple_subscription
712
813
914class LibraryResponse (BaseModel ):
1015 status : str = "Library created successfully"
1116
1217
18+ class SubscribeLibraryResponse (BaseModel ):
19+ status : str = "Subscribed in libraries successfully"
20+
21+
1322def setup ():
1423 router = APIRouter (prefix = "/libraries" , tags = ["libraries" ])
1524
@@ -24,16 +33,51 @@ async def create_library(
2433 request : Request ,
2534 body : LibrarySchema ,
2635 ):
27- await insert_library (
28- Library (
29- library_name = body .library_name ,
30- user_email = "" ,
31- releases_url = body .releases_url .encoded_string (),
32- logo = body .logo .encoded_string (),
33- ),
34- request .app .db_session_factory ,
36+ library = Library (
37+ library_name = body .library_name ,
38+ user_email = "" , # TODO: Considerar obter o email do usuário autenticado
39+ releases_url = body .releases_url .encoded_string (),
40+ logo = body .logo .encoded_string (),
3541 )
42+ try :
43+ await insert_library (library , request .app .db_session_factory )
44+ return LibraryResponse ()
45+ except Exception as e :
46+ raise HTTPException (
47+ status_code = 500 , detail = f"Failed to create library: { e } "
48+ )
49+
50+ @router .post (
51+ "/subscribe" ,
52+ response_model = SubscribeLibraryResponse ,
53+ status_code = status .HTTP_200_OK ,
54+ summary = "Subscribe to receive library updates" ,
55+ description = (
56+ "Subscribe to multiple libs and tags to receive libs updates"
57+ ),
58+ )
59+ async def subscribe_libraries (
60+ request : Request ,
61+ body : SubscriptionSchema ,
62+ ):
63+ try :
64+ library_ids = await get_library_ids_by_multiple_names (
65+ body .libraries_list , request .app .db_session_factory
66+ )
67+
68+ subscriptions = [
69+ Subscription (email = body .email , tags = body .tags , library_id = id )
70+ for id in library_ids
71+ ]
72+
73+ await upsert_multiple_subscription (
74+ subscriptions , request .app .db_session_factory
75+ )
3676
37- return LibraryResponse ()
77+ return SubscribeLibraryResponse ()
78+ except Exception as e :
79+ raise HTTPException (
80+ status_code = 500 , detail = f"Subscription failed: { e } "
81+ )
3882
3983 return router
0 commit comments