Skip to content

Commit

Permalink
fix #3 & add iterable/mapping fields support
Browse files Browse the repository at this point in the history
  • Loading branch information
yinian1992 committed Oct 25, 2023
1 parent 3a058fb commit 02777f9
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 10 deletions.
17 changes: 9 additions & 8 deletions django_rest_tsg/typescript.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import rest_framework
from inflection import camelize
from inspect import isclass
from rest_framework.serializers import (
Serializer,
BooleanField,
Expand Down Expand Up @@ -68,7 +69,7 @@
RIGHT_BRACKET = "]"
UNION_SEPARATOR = " | "

TYPESCRIPT_NULLABLE = "?"
TYPESCRIPT_NULLABLE = " | null"
TYPESCRIPT_ANY = "any"
TYPESCRIPT_STRING = "string"
TYPESCRIPT_NUMBER = "number"
Expand Down Expand Up @@ -100,7 +101,7 @@
EmailField: TYPESCRIPT_STRING,
FilePathField: TYPESCRIPT_STRING,
FloatField: TYPESCRIPT_NUMBER,
HStoreField: "{[index: string]: string?}",
HStoreField: "{[index: string]: string | null}",
IPAddressField: TYPESCRIPT_STRING,
IntegerField: TYPESCRIPT_NUMBER,
JSONField: TYPESCRIPT_ANY,
Expand Down Expand Up @@ -131,7 +132,6 @@ class TypeScriptCode:
"""
TypeScript code snippet.
"""

name: str
type: TypeScriptCodeType
source: Type[Any]
Expand Down Expand Up @@ -414,7 +414,7 @@ def get_serializer_field_type(field: Field) -> Tuple[str, list]:
result = ""
dependencies = set()
while True:
if isinstance(field, (DictField, ListField)):
if isinstance(field, (DictField, ListField)):
stack.append(type(field))
field = field.child
else:
Expand All @@ -424,10 +424,11 @@ def get_serializer_field_type(field: Field) -> Tuple[str, list]:
stack.append(field_type)
break
for item in reversed(stack):
if item is ListField:
result += "[]"
elif item is DictField:
result = f"{{[index: string]: {result}}}"
if isclass(item):
if issubclass(item, ListField):
result += "[]"
elif issubclass(item, DictField):
result = f"{{[index: string]: {result}}}"
else:
result = item
return result, sorted(list(dependencies), key=lambda tp: tp.__name__)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_dataclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
publicKeys: Array<string>;
matrix: Array<Array<any>>;
configs: Array<object>;
isStaff: boolean?;
isStaff: boolean | null;
eloRank: {[key: string]: number};
magicNumber: 42;
buttonType: ButtonType;
Expand Down
2 changes: 1 addition & 1 deletion tests/test_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
publicKeys: string[];
matrix: any[][];
configs: {[index: string]: any}[];
isStaff: boolean?;
isStaff: boolean | null;
eloRank: {[index: string]: number};
magicNumber: 42;
buttonType: ButtonType;
Expand Down

0 comments on commit 02777f9

Please sign in to comment.