|
| 1 | +import dataclasses |
| 2 | +import json |
| 3 | +import typing |
| 4 | + |
| 5 | +import azure.functions as func |
| 6 | + |
| 7 | +from ... import _domain |
| 8 | +from ... import _infrastructure |
| 9 | +from time_tracker._infrastructure import DB |
| 10 | + |
| 11 | + |
| 12 | +def create_customer(req: func.HttpRequest) -> func.HttpResponse: |
| 13 | + try: |
| 14 | + database = DB() |
| 15 | + customer_dao = _infrastructure.CustomersSQLDao(database) |
| 16 | + customer_service = _domain.CustomerService(customer_dao) |
| 17 | + use_case = _domain._use_cases.CreateCustomerUseCase(customer_service) |
| 18 | + customer_data = req.get_json() |
| 19 | + |
| 20 | + customer_is_valid = _validate_customer(customer_data) |
| 21 | + if not customer_is_valid: |
| 22 | + raise ValueError |
| 23 | + |
| 24 | + customer_to_create = _domain.Customer( |
| 25 | + id=None, |
| 26 | + deleted=None, |
| 27 | + status=None, |
| 28 | + name=str(customer_data["name"]).strip(), |
| 29 | + description=str(customer_data["description"]), |
| 30 | + ) |
| 31 | + created_customer = use_case.create_customer(customer_to_create) |
| 32 | + |
| 33 | + if created_customer: |
| 34 | + body = json.dumps(created_customer.__dict__) |
| 35 | + status_code = 201 |
| 36 | + else: |
| 37 | + body = b'This customer already exists' |
| 38 | + status_code = 409 |
| 39 | + |
| 40 | + return func.HttpResponse( |
| 41 | + body=body, |
| 42 | + status_code=status_code, |
| 43 | + mimetype="application/json" |
| 44 | + ) |
| 45 | + except ValueError: |
| 46 | + return func.HttpResponse( |
| 47 | + body=b'Invalid format or structure of the attributes of the customer', |
| 48 | + status_code=400, |
| 49 | + mimetype="application/json" |
| 50 | + ) |
| 51 | + |
| 52 | + |
| 53 | +def _validate_customer(customer_data: dict) -> bool: |
| 54 | + if [field.name for field in dataclasses.fields(_domain.Customer) |
| 55 | + if (field.name not in customer_data) and (field.type != typing.Optional[field.type])]: |
| 56 | + return False |
| 57 | + return True |
0 commit comments