Skip to content

Commit

Permalink
Refactor: licenses
Browse files Browse the repository at this point in the history
  • Loading branch information
Anuj-Gupta4 committed Aug 22, 2024
1 parent 91f5a4b commit 2658016
Show file tree
Hide file tree
Showing 3 changed files with 106 additions and 68 deletions.
73 changes: 34 additions & 39 deletions backend/api/licenses/resources.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
from backend.models.dtos.licenses_dto import LicenseDTO
from backend.models.dtos.user_dto import AuthUserDTO
from backend.models.postgis.user import User
from backend.services.license_service import LicenseService
from backend.services.users.authentication_service import tm
from backend.services.users.authentication_service import tm, login_required
from fastapi import APIRouter, Depends, Request
from backend.db import get_session
from starlette.authentication import requires
from loguru import logger
from databases import Database
from backend.db import get_db


router = APIRouter(
prefix="/licenses",
Expand All @@ -13,11 +18,12 @@
responses={404: {"description": "Not found"}},
)

# class LicensesRestAPI(Resource):

@router.post("/")
@requires("authenticated")
@tm.pm_only()
def post(request: Request):
# TODO: refactor decorator functions
# @requires("authenticated")
# @tm.pm_only()
async def post(license_dto: LicenseDTO, db: Database = Depends(get_db)):
"""
Creates a new mapping license
---
Expand Down Expand Up @@ -57,21 +63,15 @@ def post(request: Request):
500:
description: Internal Server Error
"""
try:
license_dto = LicenseDTO(request.get_json())
license_dto.validate()
except Exception as e:
logger.error(f"Error validating request: {str(e)}")
return {
"Error": "Unable to create new mapping license",
"SubCode": "InvalidData",
}, 400

new_license_id = LicenseService.create_licence(license_dto)
new_license_id = await LicenseService.create_license(license_dto, db)
return {"licenseId": new_license_id}, 201


@router.get("/{license_id}/")
async def get(request: Request, license_id):
async def get(
license_id: int,
db: Database = Depends(get_db),
):
"""
Get a specified mapping license
---
Expand All @@ -94,13 +94,16 @@ async def get(request: Request, license_id):
500:
description: Internal Server Error
"""
license_dto = LicenseService.get_license_as_dto(license_id)
return license_dto.model_dump(by_alias=True), 200
license_dto = await LicenseService.get_license_as_dto(license_id, db)
return license_dto


@router.patch("/{license_id}/")
@requires("authenticated")
@tm.pm_only()
async def patch(request: Request, license_id):
# @requires("authenticated")
# @tm.pm_only()
async def patch(
license_dto: LicenseDTO, license_id: int, db: Database = Depends(get_db)
):
"""
Update a specified mapping license
---
Expand Down Expand Up @@ -146,21 +149,14 @@ async def patch(request: Request, license_id):
500:
description: Internal Server Error
"""
try:
license_dto = LicenseDTO(request.json())
license_dto.license_id = license_id
license_dto.validate()
except Exception as e:
logger.error(f"Error validating request: {str(e)}")
return {"Error": str(e), "SubCode": "InvalidData"}, 400
await LicenseService.update_license(license_dto, license_id, db)
return {"status": "Updated"}, 200

updated_license = LicenseService.update_licence(license_dto)
return updated_license.model_dump(by_alias=True), 200

@router.delete("/{license_id}/")
@requires("authenticated")
@tm.pm_only()
async def delete(request: Request, license_id):
# @requires("authenticated")
# @tm.pm_only()
async def delete(license_id: int, db: Database = Depends(get_db)):
"""
Delete a specified mapping license
---
Expand Down Expand Up @@ -191,13 +187,12 @@ async def delete(request: Request, license_id):
500:
description: Internal Server Error
"""
LicenseService.delete_license(license_id)
await LicenseService.delete_license(license_id, db)
return {"Success": "License deleted"}, 200


# class LicensesAllAPI(Resource):
@router.get("/")
async def get():
async def get(db: Database = Depends(get_db)):
"""
Get all imagery licenses
---
Expand All @@ -213,5 +208,5 @@ async def get():
500:
description: Internal Server Error
"""
licenses_dto = LicenseService.get_all_licenses()
return licenses_dto.model_dump(by_alias=True), 200
licenses_dto = await LicenseService.get_all_licenses(db)
return licenses_dto
30 changes: 18 additions & 12 deletions backend/models/postgis/licenses.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from backend.exceptions import NotFound
from backend.models.dtos.licenses_dto import LicenseDTO, LicenseListDTO
from backend.db import Base, get_session
from databases import Database
from icecream import ic
session = get_session()

# Secondary table defining the many-to-many join
Expand Down Expand Up @@ -38,19 +40,23 @@ def get_by_id(license_id: int):
raise NotFound(sub_code="LICENSE_NOT_FOUND", license_id=license_id)

return map_license

@classmethod
def create_from_dto(cls, dto: LicenseDTO) -> int:

async def create_from_dto(license_dto: LicenseDTO, db: Database) -> int:
"""Creates a new License class from dto"""
new_license = cls()
new_license.name = dto.name
new_license.description = dto.description
new_license.plain_text = dto.plain_text

session.add(new_license)
session.commit()

return new_license.id
query = """
INSERT INTO licenses (name, description, plain_text)
VALUES (:name, :description, :plain_text)
RETURNING id
"""
values = {
"name": license_dto.name,
"description": license_dto.description,
"plain_text": license_dto.plain_text,
}

async with db.transaction():
new_license_id = await db.execute(query, values)
return new_license_id

def update_license(self, dto: LicenseDTO):
"""Update existing license"""
Expand Down
71 changes: 54 additions & 17 deletions backend/services/license_service.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from backend.models.dtos.licenses_dto import LicenseDTO, LicenseListDTO
from backend.models.postgis.licenses import License
from databases import Database
from backend.db import get_db
from fastapi import Depends, Request, HTTPException


class LicenseService:
@staticmethod
def get_license(license_id: int) -> License:
def get_license(license_id: int, db:Database) -> License:
"""
Get task from DB
:raises: NotFound
Expand All @@ -13,31 +16,65 @@ def get_license(license_id: int) -> License:
return map_license

@staticmethod
def get_license_as_dto(license_id: int) -> LicenseDTO:
async def get_license_as_dto(license_id: int, db:Database) -> LicenseDTO:
"""Get License from DB"""
map_license = LicenseService.get_license(license_id)
return map_license.as_dto()
query = """
SELECT id AS "licenseId", name, description, plain_text AS "plainText"
FROM licenses
WHERE id = :license_id
"""
license_dto = await db.fetch_one(query, {"license_id": license_id})
return LicenseDTO(**license_dto)

@staticmethod
def create_licence(license_dto: LicenseDTO) -> int:
async def create_license(license_dto: LicenseDTO, db:Database) -> int:
"""Create License in DB"""
new_licence_id = License.create_from_dto(license_dto)
return new_licence_id
new_license_id = await License.create_from_dto(license_dto, db)
return new_license_id

@staticmethod
def update_licence(license_dto: LicenseDTO) -> LicenseDTO:
async def update_license(license_dto: LicenseDTO, license_id: int, db: Database) -> LicenseDTO:
"""Create License in DB"""
map_license = LicenseService.get_license(license_dto.license_id)
map_license.update_license(license_dto)
return map_license.as_dto()

query = """
UPDATE licenses
SET name = :name, description = :description, plain_text = :plain_text
WHERE id = :license_id
"""

values = {
"name": license_dto.name,
"description": license_dto.description,
"plain_text": license_dto.plain_text,
}
await db.execute(query, values={**values, 'license_id': license_id})

@staticmethod
def delete_license(license_id: int):
async def delete_license(license_id: int, db: Database):
"""Delete specified license"""
map_license = LicenseService.get_license(license_id)
map_license.delete()
query = """
DELETE FROM licenses
WHERE id = :license_id;
"""
try:
async with db.transaction():
await db.execute(query, {"license_id": license_id})
except Exception as e:
raise HTTPException(
status_code=500, detail="Deletion failed"
) from e

@staticmethod
def get_all_licenses() -> LicenseListDTO:
"""Get all licenses in DB"""
return License.get_all()
async def get_all_licenses(db: Database) -> LicenseListDTO:
"""Gets all licenses currently stored"""
query = """
SELECT id AS "licenseId", name, description, plain_text AS "plainText"
FROM licenses
"""
results = await db.fetch_all(query)

lic_dto = LicenseListDTO()
for record in results:
l_dto = LicenseDTO(**record)
lic_dto.licenses.append(l_dto)
return lic_dto

0 comments on commit 2658016

Please sign in to comment.