Skip to content

Commit dbcd74f

Browse files
committed
refactor: database dependency injected with Database abstract class
1 parent 7b03b99 commit dbcd74f

6 files changed

Lines changed: 31 additions & 26 deletions

File tree

src/controllers/_helpers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def get_current_user(token: token_dependency) -> dict[str, Any]:
1616
if not user_id:
1717
raise HTTPException(status_code=401, detail="Usuário não autorizado")
1818

19-
user = UserService().view(user_id)
19+
user = UserService(PgDatabase()).view(user_id)
2020
if not user:
2121
raise HTTPException(status_code=404, detail="Usuário não encontrado")
2222

src/controllers/authController.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from datetime import timedelta
22
from fastapi import APIRouter, HTTPException, Header
33

4+
from src.infra.database.database import PgDatabase
45
from src.services.userService import UserService
56
from ._helpers import user_dependency, form_auth_dependency
67
from src.infra.security.hashing import (
@@ -21,7 +22,7 @@
2122
@router.post("/login")
2223
def login(form_data: form_auth_dependency):
2324
email = form_data.username.lower()
24-
user = UserService().view_by_email(email)
25+
user = UserService(PgDatabase()).view_by_email(email)
2526

2627
if not user:
2728
raise HTTPException(
@@ -56,7 +57,7 @@ def refresh(refresh_token: str = Header(..., alias="X-Refresh-Token")):
5657
payload = decode_token(refresh_token, JWT_REFRESH_SECRET_KEY, [ALGORITHM])
5758
user_id = int(payload["sub"])
5859

59-
user = UserService().view(user_id)
60+
user = UserService(PgDatabase()).view(user_id)
6061
if not user:
6162
raise HTTPException(
6263
status_code=401, detail={"message": "User not found", "error": True}

src/controllers/userController.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from fastapi import APIRouter, Depends, Request
33

44
from ._helpers import PermissionChecker
5+
from src.infra.database import PgDatabase
56
from src.services.userService import UserService
67
from src.schemas.userSchema import UserAddSchema, UserEditSchema
78

@@ -18,12 +19,12 @@ def user_all(
1819
show_fk_id: int | None = 1,
1920
perms=Depends(PermissionChecker("usuario-all")),
2021
):
21-
return UserService().all(request.query_params)
22+
return UserService(PgDatabase()).all(request.query_params)
2223

2324

2425
@router.get("/{user_id:int}")
2526
def user_view(user_id: int, perms=Depends(PermissionChecker("usuario-view"))):
26-
user = UserService().view(user_id)
27+
user = UserService(PgDatabase()).view(user_id)
2728

2829
if user is None:
2930
return JSONResponse(
@@ -36,7 +37,7 @@ def user_view(user_id: int, perms=Depends(PermissionChecker("usuario-view"))):
3637

3738
@router.post("/")
3839
def user_add(user: UserAddSchema, perms=Depends(PermissionChecker("usuario-add"))):
39-
inserted_id = UserService().add(user)
40+
inserted_id = UserService(PgDatabase()).add(user)
4041
return JSONResponse(
4142
status_code=200,
4243
content={
@@ -51,15 +52,15 @@ def user_add(user: UserAddSchema, perms=Depends(PermissionChecker("usuario-add")
5152
def user_edit(
5253
user_id: int, user: UserEditSchema, perms=Depends(PermissionChecker("usuario-edit"))
5354
):
54-
UserService().edit(user_id, user)
55+
UserService(PgDatabase()).edit(user_id, user)
5556
return JSONResponse(
5657
status_code=200, content={"error": False, "message": "User edited successfully"}
5758
)
5859

5960

6061
@router.delete("/{user_id:int}")
6162
def user_delete(user_id: int, perms=Depends(PermissionChecker("usuario-delete"))):
62-
UserService().delete(user_id)
63+
UserService(PgDatabase()).delete(user_id)
6364
return JSONResponse(
6465
status_code=200,
6566
content={"error": False, "message": "User deleted successfully"},

src/controllers/userTypeController.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from fastapi import APIRouter, Depends, Request
33

44
from ._helpers import PermissionChecker
5+
from src.infra.database import PgDatabase
56
from src.schemas.userTypeSchema import UserTypeSchema
67
from src.services.userTypeService import UserTypeService
78

@@ -16,14 +17,14 @@ def user_type_all(
1617
sort_by: str | None = None,
1718
perms=Depends(PermissionChecker("tipo_usuario-all")),
1819
):
19-
return UserTypeService().all(request.query_params)
20+
return UserTypeService(PgDatabase()).all(request.query_params)
2021

2122

2223
@router.get("/{user_type_id:int}")
2324
def user_type_view(
2425
user_type_id: int, perms=Depends(PermissionChecker("tipo_usuario-view"))
2526
):
26-
user_type = UserTypeService().view(user_type_id)
27+
user_type = UserTypeService(PgDatabase()).view(user_type_id)
2728

2829
if user_type is None:
2930
return JSONResponse(
@@ -41,7 +42,7 @@ def user_type_view(
4142
def user_type_add(
4243
user_type: UserTypeSchema, perms=Depends(PermissionChecker("tipo_usuario-add"))
4344
):
44-
inserted_id = UserTypeService().add(user_type)
45+
inserted_id = UserTypeService(PgDatabase()).add(user_type)
4546
return JSONResponse(
4647
status_code=200,
4748
content={
@@ -58,7 +59,7 @@ def user_type_edit(
5859
user_type: UserTypeSchema,
5960
perms=Depends(PermissionChecker("tipo_usuario-edit")),
6061
):
61-
UserTypeService().edit(user_type_id, user_type)
62+
UserTypeService(PgDatabase()).edit(user_type_id, user_type)
6263
return JSONResponse(
6364
status_code=200,
6465
content={"error": False, "message": "User type edited successfully"},
@@ -69,7 +70,7 @@ def user_type_edit(
6970
def user_type_delete(
7071
user_type_id: int, perms=Depends(PermissionChecker("tipo_usuario-delete"))
7172
):
72-
UserTypeService().delete(user_type_id)
73+
UserTypeService(PgDatabase()).delete(user_type_id)
7374
return JSONResponse(
7475
status_code=200,
7576
content={"error": False, "message": "User type deleted successfully"},

src/services/userService.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from fastapi import HTTPException
44
from fastapi.datastructures import QueryParams
55

6-
from src.infra.database.database import PgDatabase
6+
from src.infra.database.database import Database
77
from src.services import paginate, fields_to_update
88
from src.infra.security.hashing import bcrypt_context
99
from src.infra.database import retrieve_table_columns
@@ -12,7 +12,8 @@
1212

1313

1414
class UserService:
15-
def __init__(self) -> None:
15+
def __init__(self, database: Database) -> None:
16+
self.database = database
1617
self.table = "usuario"
1718
self.columns = retrieve_table_columns(self.table)
1819
try:
@@ -70,7 +71,7 @@ def view(self, user_id: int) -> dict[str, Any] | None:
7071
user = None
7172

7273
try:
73-
with PgDatabase() as db:
74+
with self.database as db:
7475
db.cursor.execute(
7576
f"SELECT {self.all_columns} FROM {self.table} WHERE id = %s",
7677
(user_id,),
@@ -90,7 +91,7 @@ def view_by_email(self, email: str) -> dict[str, Any] | None:
9091
user = None
9192

9293
try:
93-
with PgDatabase() as db:
94+
with self.database as db:
9495
db.cursor.execute(
9596
f"SELECT {self.all_columns} FROM {self.table} WHERE email = %s",
9697
(email,),
@@ -110,7 +111,7 @@ def add(self, user: UserAddSchema) -> int:
110111
senha = bcrypt_context.hash(user.senha)
111112

112113
try:
113-
with PgDatabase() as db:
114+
with self.database as db:
114115
db.cursor.execute(
115116
f"INSERT INTO {self.table} (email, senha, tipo_usuario_id) VALUES (%s, %s, %s) RETURNING id",
116117
(user.email.lower(), senha, user.tipo_usuario_id),
@@ -150,7 +151,7 @@ def edit(self, user_id: int, user: UserEditSchema) -> None:
150151

151152
set_fields, set_values = fields_to_update(user_dict)
152153
try:
153-
with PgDatabase() as db:
154+
with self.database as db:
154155
db.cursor.execute(
155156
f"UPDATE {self.table} SET {set_fields} WHERE id = %s",
156157
set_values + (user_id,),
@@ -163,7 +164,7 @@ def edit(self, user_id: int, user: UserEditSchema) -> None:
163164

164165
def delete(self, user_id: int) -> None:
165166
try:
166-
with PgDatabase() as db:
167+
with self.database as db:
167168
db.cursor.execute(f"DELETE FROM {self.table} WHERE id = %s", (user_id,))
168169
db.connection.commit()
169170
except Exception:

src/services/userTypeService.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,16 @@
44
from psycopg2.errors import UniqueViolation
55
from fastapi.datastructures import QueryParams
66

7-
from src.infra.database.database import PgDatabase
7+
from src.infra.database.database import Database, PgDatabase
88
from src.services import paginate, fields_to_update
99
from src.infra.database import retrieve_table_columns
1010
from src.schemas.userTypeSchema import UserTypeSchema
1111
from src.infra.database.serializers import line_to_dict
1212

1313

1414
class UserTypeService:
15-
def __init__(self) -> None:
15+
def __init__(self, database: Database) -> None:
16+
self.database = database
1617
self.table: str = "tipo_usuario"
1718
self.columns: list[str] = retrieve_table_columns(self.table)
1819
try:
@@ -65,7 +66,7 @@ def view(self, user_type_id: int) -> dict[str, Any] | None:
6566
user_type = None
6667

6768
try:
68-
with PgDatabase() as db:
69+
with self.database as db:
6970
db.cursor.execute(
7071
f"SELECT {self.all_columns} FROM {self.table} WHERE id = %s",
7172
(user_type_id,),
@@ -83,7 +84,7 @@ def view(self, user_type_id: int) -> dict[str, Any] | None:
8384

8485
def add(self, user_type: UserTypeSchema) -> int:
8586
try:
86-
with PgDatabase() as db:
87+
with self.database as db:
8788
db.cursor.execute(
8889
f"INSERT INTO {self.table} (nome) VALUES (%s) RETURNING id",
8990
(user_type.nome,),
@@ -125,7 +126,7 @@ def edit(self, user_type_id: int, user_type: UserTypeSchema) -> None:
125126

126127
set_fields, set_values = fields_to_update(user_type_dict)
127128
try:
128-
with PgDatabase() as db:
129+
with self.database as db:
129130
db.cursor.execute(
130131
f"UPDATE {self.table} SET {set_fields} WHERE id = %s",
131132
set_values + (user_type_id,),
@@ -142,7 +143,7 @@ def edit(self, user_type_id: int, user_type: UserTypeSchema) -> None:
142143

143144
def delete(self, user_type_id: int) -> None:
144145
try:
145-
with PgDatabase() as db:
146+
with self.database as db:
146147
db.cursor.execute(
147148
f"DELETE FROM {self.table} WHERE id = %s", (user_type_id,)
148149
)

0 commit comments

Comments
 (0)