forked from asyncapi/modelina
/
Pydantic.ts
53 lines (46 loc) · 1.76 KB
/
Pydantic.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { ConstrainedUnionModel } from '../../../models';
import { PythonOptions } from '../PythonGenerator';
import { ClassPresetType, PythonPreset } from '../PythonPreset';
const PYTHON_PYDANTIC_CLASS_PRESET: ClassPresetType<PythonOptions> = {
async self({ renderer, model }) {
renderer.dependencyManager.addDependency(
'from typing import Optional, Any, Union'
);
renderer.dependencyManager.addDependency(
'from pydantic import BaseModel, Field'
);
const defaultClassString = await renderer.defaultSelf();
return defaultClassString.replace(
`class ${model.name}:`,
`class ${model.name}(BaseModel):`
);
},
property(params) {
let type = params.property.property.type;
const propertyName = params.property.propertyName;
if (params.property.property instanceof ConstrainedUnionModel) {
const unionTypes = params.property.property.union.map(
(unionModel) => unionModel.type
);
type = `Union[${unionTypes.join(', ')}]`;
}
if (!params.property.required) {
type = `Optional[${type}]`;
}
const description = params.property.property.originalInput['description']
? `description='''${params.property.property.originalInput['description']}'''`
: undefined;
const defaultValue = params.property.required ? undefined : 'default=None';
const jsonAlias = `serialization_alias='${params.property.unconstrainedPropertyName}'`;
const fieldTags = [description, defaultValue, jsonAlias].filter(
(value) => value
);
return `${propertyName}: ${type} = Field(${fieldTags.join(', ')})`;
},
ctor: () => '',
getter: () => '',
setter: () => ''
};
export const PYTHON_PYDANTIC_PRESET: PythonPreset<PythonOptions> = {
class: PYTHON_PYDANTIC_CLASS_PRESET
};