Skip to content

Commit

Permalink
wip on SerializerCog
Browse files Browse the repository at this point in the history
  • Loading branch information
Xenepix committed Nov 24, 2024
1 parent 043bb8e commit 724ec6b
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
57 changes: 56 additions & 1 deletion backend/nango/cogs/serializer_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,69 @@


class SerializerCog(AbstractCog):
"""Generate serializer from each django's models.
"""Generates a serializer from each django's models.
Settings:
--------
- speedy: A faster serializer than rest_framework.serializers.Serializer, but with less features.
"""

id = "serializer"

def _get_drf_imports(self) -> list[str]:
"""Return list of imports from rest_framework module."""
if self.settings.get("speedy", False):
error_msg: str = "The SerializerCog speedy feature is not implemented yet."
raise NotImplementedError(error_msg)

return [
"from rest_framework import serializers" if not self.settings.get("speedy", False) else "...",
]

def _get_base_imports(self) -> list[str]:
"""Return basics imports."""
return [
"from __future__ import annotations",
"from typing import ClassVar",
]

def get_serializer_name(self) -> dict[str]:
"""Return name of generated serializers.
Returns:
-------
```
{
"cached_serializer_name": str,
"customizable_serializer_name": str,
}
```
"""
return {
"cached_serializer_name": f"{self.model.__name__}NangoSerializer",
"customizable_serializer_name": f"{self.model.__name__}Serializer",
}

def generate_cached_serializer(self) -> None:
"""Generate the serializer file (for the given model) that will be cached in the _nango_cache."""
content: str = f"""
{'\n'.join(self._get_base_imports())}
{'\n'.join(self._get_drf_imports())}
{self._get_model_import()}
class {self.get_serializer_name().get('cached_serializer_name')}(serializer.Serializer):
\"\"\"...generated...\"\"\"
class Meta:
model = {self.model.__name__}
"""
print(content) # noqa: T201

def generated_customizable_serializer(self) -> None:
"""Generate the serializer file (for the given model) that use the cached serializer and that can be custom by the dev."""

def run(self) -> None:
"""Generate a serializer for each django's model."""
super().run()
self.generate_cached_serializer()
self.generated_customizable_serializer()
2 changes: 1 addition & 1 deletion backend/nango/utils/abstract_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def is_executable(self) -> bool:
"""Indicate if the cog can run or not."""
return self.settings is not None

def _generate_model_import(self) -> str:
def _get_model_import(self) -> str:
"""Return the model import line for file generation."""
regex = r"(?<=')(.*)(?=\.)"
match = re.search(regex, str(self.model))
Expand Down

0 comments on commit 724ec6b

Please sign in to comment.