1
- from fastapi import APIRouter , Request , status
1
+ from fastapi import APIRouter , HTTPException , Request , status
2
2
from pydantic import BaseModel
3
3
4
4
from 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
7
12
8
13
9
14
class LibraryResponse (BaseModel ):
10
15
status : str = "Library created successfully"
11
16
12
17
18
+ class SubscribeLibraryResponse (BaseModel ):
19
+ status : str = "Subscribed in libraries successfully"
20
+
21
+
13
22
def setup ():
14
23
router = APIRouter (prefix = "/libraries" , tags = ["libraries" ])
15
24
@@ -24,16 +33,51 @@ async def create_library(
24
33
request : Request ,
25
34
body : LibrarySchema ,
26
35
):
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 (),
35
41
)
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
+ )
36
76
37
- return LibraryResponse ()
77
+ return SubscribeLibraryResponse ()
78
+ except Exception as e :
79
+ raise HTTPException (
80
+ status_code = 500 , detail = f"Subscription failed: { e } "
81
+ )
38
82
39
83
return router
0 commit comments