Skip to content
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

Include generated examples #16

Open
wants to merge 2 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
28 changes: 22 additions & 6 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@ import "ace-builds/src-noconflict/theme-monokai";

const apiUrl = "https://ufgjji253b.execute-api.us-east-1.amazonaws.com/prod";
const defaultJsonObject = '{\n\t"foo": 5, \n\t"barBaz": "hello"\n}';
const defaultOptions = { forceOptional: false, snakeCased: false };
const defaultOptions = { forceOptional: false, snakeCased: false, includeExamples: false };
const loadingMessage = "# loading...";
const invalidJsonMessage = "# invalid json";

type RequestOptions = {
forceOptional: boolean;
snakeCased: boolean;
includeExamples: boolean;
};

type RequestBody = {
Expand All @@ -30,7 +31,7 @@ function App() {

useEffect(() => {
if (validJson(jsonObject)) {
fetchConversion(jsonObject, options.forceOptional, options.snakeCased);
fetchConversion(jsonObject, options.forceOptional, options.snakeCased, options.includeExamples);
} else {
setPydanticModel(invalidJsonMessage);
}
Expand All @@ -52,11 +53,12 @@ function App() {
function fetchConversion(
newValue: string,
forceOptional: boolean,
snakeCased: boolean
snakeCased: boolean,
includeExamples: boolean
) {
console.log("fetching");
setPydanticModel(loadingMessage);
const requestOptions: RequestOptions = { forceOptional, snakeCased };
const requestOptions: RequestOptions = { forceOptional, snakeCased, includeExamples };
const requestBody: RequestBody = {
data: newValue,
options: requestOptions,
Expand Down Expand Up @@ -124,8 +126,8 @@ function App() {
</label>
</p>
</div>
<div className="field">
<p className="option">
<div className="option">
<p className="control">
<label className="checkbox">
<input
type="checkbox"
Expand All @@ -138,6 +140,20 @@ function App() {
</label>
</p>
</div>
<div className="field">
<p className="option">
<label className="checkbox">
<input
type="checkbox"
checked={options.includeExamples}
onChange={(e) =>
setOptions({ ...options, includeExamples: e.target.checked })
}
/>
Include examples for strings and numbers on the Fields.
</label>
</p>
</div>
</div>
<br></br>
<div className="about">
Expand Down
2 changes: 2 additions & 0 deletions server/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
class Options(BaseModel):
force_optional: bool = Field(False, alias="forceOptional")
snake_cased: bool = Field(False, alias="snakeCased")
include_examples: bool = Field(False, alias="includeExamples")


class BasicRequest(BaseModel):
Expand All @@ -39,6 +40,7 @@ async def convert(basic_request: BasicRequest):
basic_request.data,
options.force_optional,
options.snake_cased,
options.include_examples,
)
}

Expand Down
37 changes: 35 additions & 2 deletions server/app/scripts/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,44 @@
from pydantic import Json
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
from genson import SchemaBuilder
from genson.schema.strategies import String, Number


class StringWithExample(String):

def add_object(self, obj):
super().add_object(obj)
if not hasattr(self, "example"):
self.example = obj

def to_schema(self):
schema = super().to_schema()
if hasattr(self, "example"):
schema['example'] = self.example
return schema


class NumberWithExample(Number):
def add_object(self, obj):
super().add_object(obj)
if not hasattr(self, "example"):
self.example = obj

def to_schema(self):
schema = super().to_schema()
if hasattr(self, "example"):
schema['example'] = self.example
return schema


class ExampleSchemaBuilder(SchemaBuilder):
EXTRA_STRATEGIES = (StringWithExample, NumberWithExample)


def translate(
input_text: Union[Json, Dict[str, Any]], all_optional: bool, snake_case_field: bool
input_text: Union[Json, Dict[str, Any]], all_optional: bool, snake_case_field: bool, include_examples: bool = False
) -> str:
builder = SchemaBuilder()
builder = ExampleSchemaBuilder() if include_examples else SchemaBuilder()
builder.add_object(input_text)
schema = builder.to_schema()
if all_optional:
Expand All @@ -18,6 +50,7 @@ def translate(
source=json.dumps(schema),
base_class="pydantic.BaseModel",
snake_case_field=snake_case_field,
field_extra_keys={"example"} if include_examples else {},
)

return parser.parse()