Skip to content

Commit c02b505

Browse files
refactors repositories
1 parent 169a8c7 commit c02b505

File tree

6 files changed

+253
-164
lines changed

6 files changed

+253
-164
lines changed

lib/repositories/__init__.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1 @@
11
# lib/controllers/__init__.py
2-
3-
4-
def parse_error(error):
5-
exc_type = type(error).__name__
6-
exc_obj = f"{error}".replace("\n", " ").replace(" ", " ")
7-
return f"{exc_type} exception: {exc_obj}"

lib/repositories/environment.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from typing import Union
2-
from lib import logging
3-
from lib.repositories import parse_error
2+
from lib import logging, parse_error
43
from lib.models.environment import Env
54
from lib.repositories.repo import Repository
65

@@ -30,15 +29,15 @@ def __del__(self):
3029
super().__del__()
3130

3231
@property
33-
def env(self) -> "Env":
32+
def env(self) -> Env:
3433
return self._env
3534

3635
@env.setter
3736
def env(self, environment: "Env"):
3837
self._env = environment
3938

4039
@property
41-
def env_id(self) -> "str":
40+
def env_id(self) -> str:
4241
return self._env_id
4342

4443
@env_id.setter
@@ -64,7 +63,7 @@ async def create_env(self):
6463
return self
6564
finally:
6665
logger.info(
67-
f"Call to repositories.environment.create_env completed; states: EnvID {self.env_id}"
66+
f"Call to repositories.environment.create_env completed for Env {self.env_id}"
6867
)
6968

7069
async def update_env(self):
@@ -89,10 +88,10 @@ async def update_env(self):
8988
return self
9089
finally:
9190
logger.info(
92-
f"Call to repositories.environment.update_env completed; states: Env {hash(self.env)}, EnvID {self.env_id}"
91+
f"Call to repositories.environment.update_env completed for Env {self.env_id}"
9392
)
9493

95-
async def get_env(self) -> "Union[Env, None]":
94+
async def get_env(self) -> Union[Env, None]:
9695
"""
9796
Gets a models.Env from the database
9897
@@ -101,14 +100,16 @@ async def get_env(self) -> "Union[Env, None]":
101100
"""
102101
try:
103102
read_env = await self.collection.find_one({"env_id": self.env_id})
103+
parsed_env = Env.parse_obj(read_env) if read_env else None
104104
except Exception as e:
105-
logger.error(f"repositories.environment.get_env: {str(e)}")
105+
exc_str = parse_error(e)
106+
logger.error(f"repositories.environment.get_env: {exc_str}")
106107
raise Exception(f"Error getting environment: {str(e)}") from e
107108
else:
108-
return Env.parse_obj(read_env) if read_env else None
109+
return parsed_env
109110
finally:
110111
logger.info(
111-
f"Call to repositories.environment.get_env completed; states: Env {hash(self.env)}, EnvID {self.env_id}"
112+
f"Call to repositories.environment.get_env completed for Env {self.env_id}"
112113
)
113114

114115
async def delete_env(self):
@@ -121,9 +122,10 @@ async def delete_env(self):
121122
try:
122123
await self.collection.delete_one({"env_id": self.env_id})
123124
except Exception as e:
124-
logger.error(f"repositories.environment.delete_env: {str(e)}")
125+
exc_str = parse_error(e)
126+
logger.error(f"repositories.environment.delete_env: {exc_str}")
125127
raise Exception(f"Error deleting environment: {str(e)}") from e
126128
finally:
127129
logger.info(
128-
f"Call to repositories.environment.delete_env completed; states: Env {hash(self.env)}, EnvID {self.env_id}"
130+
f"Call to repositories.environment.delete_env completed for Env {self.env_id}"
129131
)

lib/repositories/flight.py

Lines changed: 78 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,114 +1,145 @@
11
from typing import Union
2-
from pymongo.results import InsertOneResult
3-
from pymongo.results import DeleteResult
2+
from lib import logging, parse_error
43
from lib.models.flight import Flight
54
from lib.repositories.repo import Repository
65

6+
logger = logging.getLogger(__name__)
7+
78

89
class FlightRepository(Repository):
910
"""
10-
Flight repository
11+
Enables database CRUD operations with models.Flight
1112
1213
Init Attributes:
13-
flight: Flight object
14-
flight_id: Flight id
14+
flight: models.Flight
15+
flight_id: str
1516
16-
Enables CRUD operations on flight objects
1717
"""
1818

1919
def __init__(self, flight: Flight = None, flight_id: str = None):
2020
super().__init__("flights")
21-
self.flight = flight
21+
self._flight = flight
2222
if flight_id:
23-
self.flight_id = flight_id
23+
self._flight_id = flight_id
2424
else:
25-
self.flight_id = self.flight.__hash__()
25+
self._flight_id = str(hash(self._flight))
2626

2727
def __del__(self):
2828
self.connection.close()
2929
super().__del__()
3030

31+
@property
32+
def flight(self) -> Flight:
33+
return self._flight
34+
35+
@flight.setter
36+
def flight(self, flight: "Flight"):
37+
self._flight = flight
38+
39+
@property
40+
def flight_id(self) -> str:
41+
return self._flight_id
42+
43+
@flight_id.setter
44+
def flight_id(self, flight_id: "str"):
45+
self._flight_id = flight_id
46+
3147
async def create_flight(
3248
self, motor_kind: str = "Solid", rocket_option: str = "Calisto"
33-
) -> "InsertOneResult":
49+
):
3450
"""
35-
Creates a flight in the database
51+
Creates a non-existing models.Flight in the database
3652
3753
Args:
38-
rocketpy_flight: rocketpy flight object
54+
rocket_option: models.rocket.RocketOptions
55+
motor_kind: models.motor.MotorKinds
3956
4057
Returns:
41-
InsertOneResult: result of the insert operation
58+
self
4259
"""
43-
if not await self.get_flight():
44-
try:
45-
flight_to_dict = self.flight.dict()
46-
flight_to_dict["flight_id"] = self.flight_id
47-
flight_to_dict["rocket"]["rocket_option"] = rocket_option
48-
flight_to_dict["rocket"]["motor"]["motor_kind"] = motor_kind
49-
return await self.collection.insert_one(flight_to_dict)
50-
except Exception as e:
51-
raise Exception(f"Error creating flight: {str(e)}") from e
52-
finally:
53-
self.__del__()
60+
try:
61+
flight_to_dict = self.flight.dict()
62+
flight_to_dict["flight_id"] = self.flight_id
63+
flight_to_dict["rocket"]["rocket_option"] = rocket_option
64+
flight_to_dict["rocket"]["motor"]["motor_kind"] = motor_kind
65+
await self.collection.insert_one(flight_to_dict)
66+
except Exception as e:
67+
exc_str = parse_error(e)
68+
logger.error(f"repositories.flight.create_flight: {exc_str}")
69+
raise Exception(f"Error creating flight: {str(e)}") from e
5470
else:
55-
return InsertOneResult(acknowledged=True, inserted_id=None)
71+
return self
72+
finally:
73+
logger.info(
74+
f"Call to repositories.flight.create_flight completed for Flight {self.flight_id}"
75+
)
5676

5777
async def update_flight(
5878
self, motor_kind: str = "Solid", rocket_option: str = "Calisto"
59-
) -> "Union[str, None]":
79+
):
6080
"""
61-
Updates a flight in the database
81+
Updates a models.Flight in the database
6282
6383
Returns:
64-
int: flight id
84+
self
6585
"""
6686
try:
6787
flight_to_dict = self.flight.dict()
68-
flight_to_dict["flight_id"] = self.flight.__hash__()
88+
flight_to_dict["flight_id"] = str(hash(self.flight))
6989
flight_to_dict["rocket"]["rocket_option"] = rocket_option
7090
flight_to_dict["rocket"]["motor"]["motor_kind"] = motor_kind
71-
7291
await self.collection.update_one(
7392
{"flight_id": self.flight_id}, {"$set": flight_to_dict}
7493
)
7594
self.flight_id = flight_to_dict["flight_id"]
7695
except Exception as e:
96+
exc_str = parse_error(e)
97+
logger.error(f"repositories.flight.update_flight: {exc_str}")
7798
raise Exception(f"Error updating flight: {str(e)}") from e
78-
else:
79-
return str(self.flight_id)
8099
finally:
81-
self.__del__()
100+
logger.info(
101+
f"Call to repositories.flight.update_flight completed for Flight {self.flight_id}"
102+
)
82103

83-
async def get_flight(self) -> "Union[Flight, None]":
104+
async def get_flight(self) -> Union[Flight, None]:
84105
"""
85-
Gets a flight from the database
106+
Gets a models.Flight from the database
86107
87108
Returns:
88-
models.Flight: Model flight object
109+
models.Flight
89110
"""
90111
try:
91-
flight = await self.collection.find_one(
112+
read_flight = await self.collection.find_one(
92113
{"flight_id": self.flight_id}
93114
)
94-
if flight is not None:
95-
return Flight.parse_obj(flight)
96-
return None
115+
parsed_flight = (
116+
Flight.parse_obj(read_flight) if read_flight else None
117+
)
97118
except Exception as e:
119+
exc_str = parse_error(e)
120+
logger.error(f"repositories.flight.get_flight: {exc_str}")
98121
raise Exception(f"Error getting flight: {str(e)}") from e
122+
else:
123+
return parsed_flight
124+
finally:
125+
logger.info(
126+
f"Call to repositories.flight.get_flight completed for Flight {self.flight_id}"
127+
)
99128

100-
async def delete_flight(self) -> "DeleteResult":
129+
async def delete_flight(self):
101130
"""
102-
Deletes a flight from the database
131+
Deletes a models.Flight from the database
103132
104133
Returns:
105-
DeleteResult: result of the delete operation
134+
None
106135
"""
107136
try:
108-
return await self.collection.delete_one(
109-
{"flight_id": self.flight_id}
110-
)
137+
await self.collection.delete_one({"flight_id": self.flight_id})
111138
except Exception as e:
139+
exc_str = parse_error(e)
140+
logger.error(f"repositories.flight.delete_flight: {exc_str}")
112141
raise Exception(f"Error deleting flight: {str(e)}") from e
113142
finally:
114-
self.__del__()
143+
logger.info(
144+
f"Call to repositories.flight.delete_flight completed for Flight {self.flight_id}"
145+
)

0 commit comments

Comments
 (0)