Skip to content

Update for pydantic 2 #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 19 additions & 14 deletions pydantic2ts/cli/script.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@

from pydantic import BaseModel, Extra, create_model

try:
from pydantic.generics import GenericModel
except ImportError:
GenericModel = None

logger = logging.getLogger("pydantic2ts")

Expand Down Expand Up @@ -65,8 +61,9 @@ def is_concrete_pydantic_model(obj) -> bool:
return False
elif obj is BaseModel:
return False
elif GenericModel and issubclass(obj, GenericModel):
return bool(obj.__concrete__)
# Generic model was removed
# elif GenericModel and issubclass(obj, GenericModel):
# return bool(obj.__concrete__)
else:
return issubclass(obj, BaseModel)

Expand Down Expand Up @@ -137,6 +134,11 @@ def clean_schema(schema: Dict[str, Any]) -> None:
for prop in schema.get("properties", {}).values():
prop.pop("title", None)

# Work around to produce Tuples just like Arrays since json2ts doesn't support the
# prefixItems json openAPI spec
if "prefixItems" in prop:
prop["items"] = prop["prefixItems"]

if "enum" in schema and schema.get("description") == "An enumeration.":
del schema["description"]

Expand All @@ -152,30 +154,32 @@ def generate_json_schema(models: List[Type[BaseModel]]) -> str:
'[k: string]: any' from being added to every interface. This change is reverted
once the schema has been generated.
"""
model_extras = [getattr(m.Config, "extra", None) for m in models]
model_extras = [m.model_config.get("extra", None) for m in models]

try:
for m in models:
if getattr(m.Config, "extra", None) != Extra.allow:
m.Config.extra = Extra.forbid
if m.model_config.get("extra", None) != "allow":
m.model_config["extra"] = "forbid"

master_model = create_model(
"_Master_", **{m.__name__: (m, ...) for m in models}
)
master_model.Config.extra = Extra.forbid
master_model.Config.schema_extra = staticmethod(clean_schema)
master_model.model_config["extra"] = "forbid"
master_model.model_config["json_schema_extra"] = staticmethod(clean_schema)

schema = master_model.model_json_schema()

schema = json.loads(master_model.schema_json())
# prefixItems

for d in schema.get("definitions", {}).values():
for d in schema.get("$defs", {}).values():
clean_schema(d)

return json.dumps(schema, indent=2)

finally:
for m, x in zip(models, model_extras):
if x is not None:
m.Config.extra = x
m.model_config["extra"] = x


def generate_typescript_defs(
Expand Down Expand Up @@ -281,3 +285,4 @@ def main() -> None:

if __name__ == "__main__":
main()

2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def readme():

setup(
name="pydantic-to-typescript",
version="1.0.10",
version="2.0.0",
description="Convert pydantic models to typescript interfaces",
license="MIT",
long_description=readme(),
Expand Down
2 changes: 1 addition & 1 deletion tests/expected_results/excluding_models/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@

export interface Profile {
username: string;
age?: number;
age: number | null;
hobbies: string[];
}
3 changes: 1 addition & 2 deletions tests/expected_results/generics/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from typing import Generic, TypeVar, Optional, List, Type, cast, Union

from pydantic import BaseModel
from pydantic.generics import GenericModel

T = TypeVar("T")

Expand All @@ -12,7 +11,7 @@ class Error(BaseModel):
message: str


class ApiResponse(GenericModel, Generic[T]):
class ApiResponse(BaseModel, Generic[T]):
data: Optional[T]
error: Optional[Error]

Expand Down
24 changes: 14 additions & 10 deletions tests/expected_results/generics/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
/* Do not modify it by hand - just update the pydantic models and then re-run the script
*/

export interface ApiResponse {
data: unknown;
error: Error | null;
}
export interface Error {
code: number;
message: string;
}
export interface Article {
author: User;
content: string;
Expand All @@ -14,17 +22,13 @@ export interface User {
name: string;
email: string;
}
export interface Error {
code: number;
message: string;
}
export interface ListArticlesResponse {
data?: Article[];
error?: Error;
data: Article[] | null;
error: Error | null;
}
export interface ListUsersResponse {
data?: User[];
error?: Error;
data: User[] | null;
error: Error | null;
}
export interface UserProfile {
name: string;
Expand All @@ -34,6 +38,6 @@ export interface UserProfile {
age: number;
}
export interface UserProfileResponse {
data?: UserProfile;
error?: Error;
data: UserProfile | null;
error: Error | null;
}
2 changes: 1 addition & 1 deletion tests/expected_results/single_module/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ export interface LoginResponseData {
}
export interface Profile {
username: string;
age?: number;
age: number | null;
hobbies: string[];
}