Last active
December 27, 2022 16:50
-
-
Save akhundMurad/e5da45acd02404931733dfd151ea96c3 to your computer and use it in GitHub Desktop.
Example of DTO mapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import Type | |
| from automapper import create_mapper | |
| from multimethod import multimethod | |
| from src.domain.dto import ProfileDTO, UserDTO | |
| class DTOMapper: | |
| def __init__(self) -> None: | |
| self._mapper = create_mapper() | |
| @multimethod | |
| def map(self, source, target_type): | |
| ... | |
| @map.register | |
| def _(self, source: ProfileDTO, target_type: Type[UserDTO]) -> UserDTO: | |
| return self._mapper.to(target_type).map(source, fields_mapping={"id": source.uuid}) | |
| @map.register | |
| def _(self, source: PostDTO, target_type: Type[StatsDTO]) -> StatsDTO: | |
| return self._mapper.to(target_type).map(source, fields_mapping={"clicks": source.actions}) | |
| # Usage Example | |
| mapper = DTOMapper() | |
| stats_dto = mapper.map(posts_dto, StatsDTO) | |
| # Note: the multimethod library currently doesn't support typing.Type (you can use typing.Literal), | |
| # but it will be added on the next release | |
| # Issue: https://github.com/coady/multimethod/issues/78 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment