Skip to content

Commit 630ae4d

Browse files
committed
feat: v2 - convert computed fields
1 parent 21799cd commit 630ae4d

File tree

5 files changed

+48
-13
lines changed

5 files changed

+48
-13
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,4 +146,5 @@ cython_debug/
146146
.vscode
147147

148148
# test outputs
149-
output_debug.ts
149+
output_debug.ts
150+
schema_debug.json

pydantic2ts/cli/script.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,19 @@
1515

1616
from pydantic import VERSION, BaseModel, Extra, create_model
1717

18-
try:
19-
from pydantic.generics import GenericModel
20-
except ImportError:
21-
GenericModel = None
18+
V2 = True if VERSION.startswith("2") else False
19+
20+
if not V2:
21+
try:
22+
from pydantic.generics import GenericModel
23+
except ImportError:
24+
GenericModel = None
2225

2326
logger = logging.getLogger("pydantic2ts")
2427

2528

2629
DEBUG = os.environ.get("DEBUG", False)
2730

28-
V2 = True if VERSION.startswith("2") else False
29-
3031

3132
def import_module(path: str) -> ModuleType:
3233
"""
@@ -202,16 +203,16 @@ def generate_json_schema_v2(models: List[Type[BaseModel]]) -> str:
202203

203204
try:
204205
for m in models:
205-
if m.model_config.get("extra") != Extra.allow:
206-
m.model_config["extra"] = Extra.forbid
206+
if m.model_config.get("extra") != "allow":
207+
m.model_config["extra"] = "forbid"
207208

208209
master_model: BaseModel = create_model(
209210
"_Master_", **{m.__name__: (m, ...) for m in models}
210211
)
211-
master_model.model_config["extra"] = Extra.forbid
212+
master_model.model_config["extra"] = "forbid"
212213
master_model.model_config["json_schema_extra"] = staticmethod(clean_schema)
213214

214-
schema: dict = master_model.model_json_schema()
215+
schema: dict = master_model.model_json_schema(mode="serialization")
215216

216217
for d in schema.get("$defs", {}).values():
217218
clean_schema(d)
@@ -260,7 +261,9 @@ def generate_typescript_defs(
260261
f.write(schema)
261262

262263
if DEBUG:
263-
with open(Path(output).parent / "schema.json", "w") as f:
264+
debug_schema_file_path = Path(module).parent / "schema_debug.json"
265+
# raise ValueError(module)
266+
with open(debug_schema_file_path, "w") as f:
264267
f.write(schema)
265268

266269
logger.info("Converting JSON schema to typescript definitions...")
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# https://docs.pydantic.dev/latest/usage/computed_fields/
2+
3+
from pydantic import BaseModel, computed_field
4+
5+
6+
class Rectangle(BaseModel):
7+
width: int
8+
length: int
9+
10+
@computed_field
11+
@property
12+
def area(self) -> int:
13+
return self.width * self.length
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/* tslint:disable */
2+
/* eslint-disable */
3+
/**
4+
/* This file was automatically generated from pydantic models by running pydantic2ts.
5+
/* Do not modify it by hand - just update the pydantic models and then re-run the script
6+
*/
7+
8+
export interface Rectangle {
9+
width: number;
10+
length: number;
11+
area: number;
12+
}

tests/test_script.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def run_test(
4141
cmd = f"pydantic2ts --module {module_path} --output {output_path}"
4242
for model_to_exclude in exclude:
4343
cmd += f" --exclude {model_to_exclude}"
44-
subprocess.run(cmd, shell=True)
44+
subprocess.run(cmd, shell=True, check=True)
4545

4646
with open(output_path, "r") as f:
4747
output = f.read()
@@ -82,6 +82,12 @@ def test_excluding_models(tmpdir):
8282
)
8383

8484

85+
def test_computed_fields(tmpdir):
86+
if version == "v1":
87+
pytest.skip("Computed fields are a pydantic v2 feature")
88+
run_test(tmpdir, "computed_fields")
89+
90+
8591
def test_relative_filepath(tmpdir):
8692
test_name = "single_module"
8793
relative_path = os.path.join(

0 commit comments

Comments
 (0)