0

I'm asking myself a question about clean architecture.

Let's imagine a small api that allow us to create and get a user using that type of archi. This app has two endpoints and store the data in a database. Let's say that we have a db model that look like

class User:
    id: int
    firstname: str
    lastname: str

Firstly, the GET endpoint will use the usecase GetUser and use a User entity. This entity will look like:

class User:
    id: int
    firstname: str
    lastname: str

My question concerns the POST endpoint. The data passed in this endpoint is only the fields firstname and lastname, obviously. Do I have to do another entity like this one under ?

class UserRequest:
    firstname: str
    lastname: str

I found this unsatisfying because it does not make sense to imagine such an entity as a business point-of-view. Nevertheless, it seems a bit wobbly to make an entity "composite" such as:

class User:
    id: Optional[int]
    firstname: str
    lastname: str

A third option is to use a class inside the usecase file that have for only purpose to model the past coming from the POST request. ie

class UserRequest:
    firstname: str
    lastname: str

class CreateUserUseCase:
    def __init__():
        ...
    def execute(request: UserRequest):
        ...

So the question is: According to clean architecture principles, What is the best way to model data coming from a POST request that is not a business entity?

Thanks a lot for your help, and don't hesitate to ask question if my examples are not clear enough.

Stef.

1 Answers1

0

It would be helpful to view multiple endpoints (use-cases) in the context of the same entity as the lifecycle of that entity, for example:

  1. Creating (POST) a new user 'xyz' (writing to database)
  2. Mutating (POST/PUT/PATCH) user 'xyz' (writing to database)
  3. Querying (GET) user 'xyz' (reading from database)

Each of the above actions should involve the same business entity User:

  1. Creating: User entity is being constructed inside use-case (application layer) using UserRequest DTO (you have actually demonstrated exactly that) then passed to repository object for persistence.
  2. Mutating: User entity is being retrieved from database (repository object) then modified (application) finally passed to repository object for persistence.
  3. Querying: User entity is being retrieved from database (repository object) then passed back to presentation layer finally translated into response DTO.

One of the principles in CA is to have DTOs inside presentation layer being mapped to/from input/output ports. The heart of CA is domain entities, being constructed either from input (representing request DTO) or from database.

desertech
  • 911
  • 3
  • 7