Skip to content

Commit ab0478a

Browse files
Add find_by_id method to repository implementations: Implemented find_by_id methods in OrderRepositoryImpl, ParticipantRepositoryImpl, and ProductRepositoryImpl to support ID retrieval using both string and UUID types. Enhanced error handling and ID conversion logic for improved robustness.
1 parent cc980f3 commit ab0478a

File tree

3 files changed

+78
-3
lines changed

3 files changed

+78
-3
lines changed

src/infrastructure/repository/order_repository_impl.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import json
22
import logging
3-
from typing import List, Optional
3+
import uuid
4+
from typing import List, Optional, Union
45
from src.domain.entity.order import Order
56
from src.domain.repository.order_repository import OrderRepository
67
from src.infrastructure.aws.dynamodb_service import DynamoDBService
@@ -37,6 +38,35 @@ def get_by_id(self, entity_id: int) -> Optional[Order]:
3738
logger.error(f"Erro ao buscar pedido por ID {entity_id}: {str(e)}")
3839
raise
3940

41+
def find_by_id(self, entity_id: Union[str, uuid.UUID]) -> Optional[Order]:
42+
"""
43+
Busca pedido por ID, aceitando tanto string quanto UUID.
44+
Implementa o método abstrato definido na classe base BaseRepository.
45+
Nota: Como Order usa int como ID, converte string/UUID para int.
46+
"""
47+
try:
48+
# Converte para string primeiro, depois para int
49+
if isinstance(entity_id, uuid.UUID):
50+
# Se for UUID, converte para string e depois tenta extrair um int
51+
# Isso pode não ser ideal - talvez precise de uma lógica específica
52+
id_str = str(entity_id)
53+
# Por enquanto, vamos tentar usar os primeiros dígitos como int
54+
# Isso é uma solução temporária - talvez precise ajustar conforme a lógica de negócio
55+
id_int = int(id_str.replace('-', '')[:10]) # Pega os primeiros 10 dígitos
56+
else:
57+
# Se for string, tenta converter para int
58+
id_int = int(str(entity_id))
59+
60+
# Reutiliza a lógica existente do get_by_id
61+
return self.get_by_id(id_int)
62+
63+
except (ValueError, TypeError) as e:
64+
logger.error(f"Erro ao converter ID {entity_id} para int: {str(e)}")
65+
return None
66+
except Exception as e:
67+
logger.error(f"Erro ao buscar pedido por ID {entity_id}: {str(e)}")
68+
raise
69+
4070
def get_all(self) -> List[Order]:
4171

4272
try:

src/infrastructure/repository/participant_repository_impl.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import json
22
import logging
3-
from typing import List, Optional
3+
import uuid
4+
from typing import List, Optional, Union
45
from src.domain.entity.participant import Participant
56
from src.domain.repository.participant_repository import ParticipantRepository
67
from src.infrastructure.aws.dynamodb_service import DynamoDBService
@@ -35,6 +36,22 @@ def get_by_id(self, entity_id: str) -> Optional[Participant]:
3536
logger.error(f"Erro ao buscar participante por ID {entity_id}: {str(e)}")
3637
raise
3738

39+
def find_by_id(self, entity_id: Union[str, uuid.UUID]) -> Optional[Participant]:
40+
"""
41+
Busca participante por ID, aceitando tanto string quanto UUID.
42+
Implementa o método abstrato definido na classe base BaseRepository.
43+
"""
44+
try:
45+
# Converte UUID para string se necessário
46+
id_str = str(entity_id) if isinstance(entity_id, uuid.UUID) else entity_id
47+
48+
# Reutiliza a lógica existente do get_by_id
49+
return self.get_by_id(id_str)
50+
51+
except Exception as e:
52+
logger.error(f"Erro ao buscar participante por ID {entity_id}: {str(e)}")
53+
raise
54+
3855
def get_all(self) -> List[Participant]:
3956
try:
4057
items = self.dynamodb_service.scan_table(self.table_name)

src/infrastructure/repository/product_repository_impl.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import json
22
import logging
3-
from typing import List, Optional
3+
import uuid
4+
from typing import List, Optional, Union
45
from src.domain.entity.product import Product
56
from src.domain.repository.product_repository import ProductRepository
67
from src.infrastructure.aws.dynamodb_service import DynamoDBService
@@ -41,6 +42,33 @@ def get_by_id(self, entity_id: int) -> Optional[Product]:
4142
logger.error(f"Erro ao buscar produto por ID {entity_id}: {str(e)}")
4243
raise
4344

45+
def find_by_id(self, entity_id: Union[str, uuid.UUID]) -> Optional[Product]:
46+
"""
47+
Busca produto por ID, aceitando tanto string quanto UUID.
48+
Implementa o método abstrato definido na classe base BaseRepository.
49+
Nota: Como Product usa int como ID, converte string/UUID para int.
50+
"""
51+
try:
52+
# Converte para string primeiro, depois para int
53+
if isinstance(entity_id, uuid.UUID):
54+
# Se for UUID, converte para string e depois tenta extrair um int
55+
id_str = str(entity_id)
56+
# Tenta usar os primeiros dígitos como int
57+
id_int = int(id_str.replace('-', '')[:10]) # Pega os primeiros 10 dígitos
58+
else:
59+
# Se for string, tenta converter para int
60+
id_int = int(str(entity_id))
61+
62+
# Reutiliza a lógica existente do get_by_id
63+
return self.get_by_id(id_int)
64+
65+
except (ValueError, TypeError) as e:
66+
logger.error(f"Erro ao converter ID {entity_id} para int: {str(e)}")
67+
return None
68+
except Exception as e:
69+
logger.error(f"Erro ao buscar produto por ID {entity_id}: {str(e)}")
70+
raise
71+
4472
def get_all(self) -> List[Product]:
4573
try:
4674
items = self.dynamodb_service.scan_table(self.table_name)

0 commit comments

Comments
 (0)