From a01262ff8a4e58465739047ee0771d6a5492e1d2 Mon Sep 17 00:00:00 2001 From: Alexander Shabarshov Date: Tue, 25 Mar 2025 15:24:23 +0000 Subject: [PATCH] Minor nuget update. Example code generation. --- BlazorOpenApi/Controls/OperationControl.razor | 91 +++++++++++++++++++ Directory.Packages.props | 2 +- 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/BlazorOpenApi/Controls/OperationControl.razor b/BlazorOpenApi/Controls/OperationControl.razor index 2c9f2e0..4c6d678 100644 --- a/BlazorOpenApi/Controls/OperationControl.razor +++ b/BlazorOpenApi/Controls/OperationControl.razor @@ -51,6 +51,11 @@ + +
+

Example Data

+
@GenerateExampleData()
+
} } @@ -73,4 +78,90 @@ _expanded = !_expanded; StateHasChanged(); } + + private string GenerateExampleData() + { + if (Value == null) + { + return string.Empty; + } + + var exampleData = new Dictionary(); + + // Generate example data for parameters + foreach (var parameter in Value.Parameters) + { + if (parameter.Example != null) + { + exampleData[parameter.Name] = parameter.Example; + } + else if (parameter.Schema?.Example != null) + { + exampleData[parameter.Name] = parameter.Schema.Example; + } + else + { + exampleData[parameter.Name] = GenerateExampleFromSchema(parameter.Schema); + } + } + + // Generate example data for request body + if (Value.RequestBody?.Content != null) + { + foreach (var content in Value.RequestBody.Content) + { + if (content.Value.Example != null) + { + exampleData[content.Key] = content.Value.Example; + } + else if (content.Value.Schema?.Example != null) + { + exampleData[content.Key] = content.Value.Schema.Example; + } + else + { + exampleData[content.Key] = GenerateExampleFromSchema(content.Value.Schema); + } + } + } + + return JsonSerializer.Serialize(exampleData, new JsonSerializerOptions { WriteIndented = true }); + } + + private object GenerateExampleFromSchema(OpenApiSchema? schema) + { + if (schema == null) + { + return new object(); + } + + if (schema.Type == "object" && schema.Properties != null) + { + var obj = new Dictionary(); + foreach (var property in schema.Properties) + { + obj[property.Key] = GenerateExampleFromSchema(property.Value); + } + return obj; + } + + if (schema.Type == "array" && schema.Items != null) + { + return new[] { GenerateExampleFromSchema(schema.Items) }; + } + + return schema.Default ?? schema.Example ?? GetDefaultValueForType(schema.Type); + } + + private object GetDefaultValueForType(string? type) + { + return type switch + { + "string" => "string", + "integer" => 0, + "number" => 0.0, + "boolean" => false, + _ => new object() + }; + } } diff --git a/Directory.Packages.props b/Directory.Packages.props index 8fbc97e..746f381 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -8,6 +8,6 @@ - + \ No newline at end of file