REFACTOR: Moved more functionality into database base type
This commit is contained in:
@@ -2,15 +2,33 @@ from .database import DatabaseController
|
||||
from models.users.user import User
|
||||
from models.users.customer import Customer
|
||||
from models.users.seller import Seller
|
||||
from models.users.admin import Admin
|
||||
|
||||
|
||||
class UserController(DatabaseController):
|
||||
FIELDS = ['id', 'username', 'password', 'firstName',
|
||||
'lastName', 'email', 'phone', 'role']
|
||||
TYPE = User
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def convert_type(self, user: User | None
|
||||
) -> User | Customer | Seller | Admin | None:
|
||||
""" Function to convert a given user to their correct subtype """
|
||||
if user is None:
|
||||
return None
|
||||
|
||||
# Set the object to the correct type
|
||||
type = Customer
|
||||
if user.role == "Seller":
|
||||
type = Seller
|
||||
if user.role == "Admin":
|
||||
type = Admin
|
||||
|
||||
obj = self.new_instance(type, user.__dict__)
|
||||
return obj
|
||||
|
||||
def create(self, user: User):
|
||||
params = [
|
||||
user.username,
|
||||
@@ -21,62 +39,29 @@ class UserController(DatabaseController):
|
||||
user.phone,
|
||||
user.role
|
||||
]
|
||||
|
||||
self._conn.execute(
|
||||
"""INSERT INTO Users
|
||||
query = """
|
||||
INSERT INTO Users
|
||||
(username, password, first_name, last_name, email, phone, role)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)""",
|
||||
params
|
||||
)
|
||||
self._conn.commit()
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
"""
|
||||
|
||||
self.do(query, params)
|
||||
|
||||
def read(self, username: str) -> User | None:
|
||||
params = [
|
||||
username
|
||||
]
|
||||
query = "SELECT * FROM Users WHERE Username = ?"
|
||||
|
||||
cursor = self._conn.execute(
|
||||
"SELECT * FROM Users WHERE Username = ?",
|
||||
params
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
|
||||
if row is not None:
|
||||
params = dict(zip(self.FIELDS, row))
|
||||
|
||||
# Is user a seller
|
||||
type = Customer
|
||||
if row[7] == "Seller":
|
||||
type = Seller
|
||||
|
||||
obj = self.new_instance(type, params)
|
||||
return obj
|
||||
|
||||
return None
|
||||
return self.convert_type(self.get_one(query, params))
|
||||
|
||||
def read_id(self, id: int) -> User | None:
|
||||
params = [
|
||||
id
|
||||
]
|
||||
query = "SELECT * FROM Users WHERE id = ?"
|
||||
|
||||
cursor = self._conn.execute(
|
||||
"SELECT * FROM Users WHERE id = ?",
|
||||
params
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
|
||||
if row is not None:
|
||||
params = dict(zip(self.FIELDS, row))
|
||||
|
||||
# Is user a seller
|
||||
type = Customer
|
||||
if row[7] == "Seller":
|
||||
type = Seller
|
||||
|
||||
obj = self.new_instance(type, params)
|
||||
return obj
|
||||
|
||||
return None
|
||||
return self.convert_type(self.get_one(query, params))
|
||||
|
||||
def update(self):
|
||||
print("Doing work")
|
||||
|
||||
Reference in New Issue
Block a user