Skip to content

Commit

Permalink
jasontaylordev#104 - Implemented [Feature request] Use fluent validat…
Browse files Browse the repository at this point in the history
…ion rules to define swagger schema jasontaylordev#104
  • Loading branch information
Lanz86 committed Jan 27, 2023
1 parent 10ac307 commit dbea518
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 72 deletions.
28 changes: 25 additions & 3 deletions src/WebUI/ConfigureServices.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
using CleanArchitecture.Application.Common.Interfaces;
using System;
using System.Reflection;
using CleanArchitecture.Application.Common.Interfaces;
using CleanArchitecture.Application.TodoItems.Commands.CreateTodoItem;
using CleanArchitecture.Infrastructure.Persistence;
using CleanArchitecture.WebUI.Filters;
using CleanArchitecture.WebUI.Services;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using NSwag;
using NSwag.Generation.Processors.Security;
using ZymLabs.NSwag.FluentValidation;

namespace Microsoft.Extensions.DependencyInjection;

Expand All @@ -24,16 +29,33 @@ public static IServiceCollection AddWebUIServices(this IServiceCollection servic

services.AddControllersWithViews(options =>
options.Filters.Add<ApiExceptionFilterAttribute>())
.AddFluentValidation(x => x.AutomaticValidationEnabled = false);
.AddFluentValidation(x =>
{
x.AutomaticValidationEnabled = false;
}
);

services.AddRazorPages();

services.AddScoped<FluentValidationSchemaProcessor>(provider =>
{
var validationRules = provider.GetService<IEnumerable<FluentValidationRule>>();
var loggerFactory = provider.GetService<ILoggerFactory>();
return new FluentValidationSchemaProcessor(provider, validationRules, loggerFactory);
});

// Customise default API behaviour
services.Configure<ApiBehaviorOptions>(options =>
options.SuppressModelStateInvalidFilter = true);

services.AddOpenApiDocument(configure =>
services.AddOpenApiDocument((configure, serviceProvider) =>
{
var fluentValidationSchemaProcessor = serviceProvider.CreateScope().ServiceProvider.GetService<FluentValidationSchemaProcessor>();
// Add the fluent validations schema processor
configure.SchemaProcessors.Add(fluentValidationSchemaProcessor);
configure.Title = "CleanArchitecture API";
configure.AddSecurity("JWT", Enumerable.Empty<string>(), new OpenApiSecurityScheme
{
Expand Down
15 changes: 12 additions & 3 deletions src/WebUI/WebUI.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
Expand Down Expand Up @@ -30,11 +30,12 @@
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0-rc.2.22472.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.0-rc.2.22472.11" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="6.0.10" />
<PackageReference Include="NSwag.AspNetCore" Version="13.16.0" />
<PackageReference Include="NSwag.MSBuild" Version="13.16.0">
<PackageReference Include="NSwag.AspNetCore" Version="13.18.2" />
<PackageReference Include="NSwag.MSBuild" Version="13.18.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="ZymLabs.NSwag.FluentValidation.AspNetCore" Version="0.6.2" />
</ItemGroup>

<ItemGroup>
Expand All @@ -44,6 +45,14 @@
<None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
</ItemGroup>

<PropertyGroup>
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
</PropertyGroup>

<Target Name="NSwag" AfterTargets="PostBuildEvent" Condition=" '$(Configuration)' == 'Debug' ">
<Exec WorkingDirectory="$(ProjectDir)" EnvironmentVariables="ASPNETCORE_ENVIRONMENT=Development" Command="$(NSwagExe_Net70) run nswag.json /variables:Configuration=$(Configuration)" />
</Target>

<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
<!-- Ensure Node.js is installed -->
<Exec Command="node --version" ContinueOnError="true">
Expand Down
132 changes: 66 additions & 66 deletions src/WebUI/nswag.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"runtime": "Net60",
"runtime": "Net70",
"defaultVariables": null,
"documentGenerator": {
"aspNetCoreToOpenApi": {
Expand Down Expand Up @@ -59,69 +59,69 @@
"referencePaths": [],
"useNuGetCache": false
}
},
"codeGenerators": {
"openApiToTypeScriptClient": {
"className": "{controller}Client",
"moduleName": "",
"namespace": "",
"typeScriptVersion": 4.3,
"template": "Angular",
"promiseType": "Promise",
"httpClass": "HttpClient",
"withCredentials": false,
"useSingletonProvider": true,
"injectionTokenType": "InjectionToken",
"rxJsVersion": 7.0,
"dateTimeType": "Date",
"nullValue": "Undefined",
"generateClientClasses": true,
"generateClientInterfaces": true,
"generateOptionalParameters": false,
"exportTypes": true,
"wrapDtoExceptions": false,
"exceptionClass": "SwaggerException",
"clientBaseClass": null,
"wrapResponses": false,
"wrapResponseMethods": [],
"generateResponseClasses": true,
"responseClass": "SwaggerResponse",
"protectedMethods": [],
"configurationClass": null,
"useTransformOptionsMethod": false,
"useTransformResultMethod": false,
"generateDtoTypes": true,
"operationGenerationMode": "MultipleClientsFromOperationId",
"markOptionalProperties": true,
"generateCloneMethod": false,
"typeStyle": "Class",
"enumStyle": "Enum",
"useLeafType": false,
"classTypes": [],
"extendedClasses": [],
"extensionCode": null,
"generateDefaultValues": true,
"excludedTypeNames": [],
"excludedParameterNames": [],
"handleReferences": false,
"generateConstructorInterface": true,
"convertConstructorInterfaceData": false,
"importRequiredTypes": true,
"useGetBaseUrlMethod": false,
"baseUrlTokenName": "API_BASE_URL",
"queryNullValue": "",
"useAbortSignal": false,
"inlineNamedDictionaries": false,
"inlineNamedAny": false,
"includeHttpContext": false,
"templateDirectory": null,
"typeNameGeneratorType": null,
"propertyNameGeneratorType": null,
"enumNameGeneratorType": null,
"serviceHost": null,
"serviceSchemes": null,
"output": "ClientApp/src/app/web-api-client.ts",
"newLineBehavior": "Auto"
}
}
}//,
//"codeGenerators": {
// "openApiToTypeScriptClient": {
// "className": "{controller}Client",
// "moduleName": "",
// "namespace": "",
// "typeScriptVersion": 4.3,
// "template": "Angular",
// "promiseType": "Promise",
// "httpClass": "HttpClient",
// "withCredentials": false,
// "useSingletonProvider": true,
// "injectionTokenType": "InjectionToken",
// "rxJsVersion": 7.0,
// "dateTimeType": "Date",
// "nullValue": "Undefined",
// "generateClientClasses": false,
// "generateClientInterfaces": false,
// "generateOptionalParameters": false,
// "exportTypes": true,
// "wrapDtoExceptions": false,
// "exceptionClass": "SwaggerException",
// "clientBaseClass": null,
// "wrapResponses": false,
// "wrapResponseMethods": [],
// "generateResponseClasses": true,
// "responseClass": "SwaggerResponse",
// "protectedMethods": [],
// "configurationClass": null,
// "useTransformOptionsMethod": false,
// "useTransformResultMethod": false,
// "generateDtoTypes": true,
// "operationGenerationMode": "MultipleClientsFromOperationId",
// "markOptionalProperties": false,
// "generateCloneMethod": false,
// "typeStyle": "Class",
// "enumStyle": "Enum",
// "useLeafType": false,
// "classTypes": [],
// "extendedClasses": [],
// "extensionCode": null,
// "generateDefaultValues": true,
// "excludedTypeNames": [],
// "excludedParameterNames": [],
// "handleReferences": false,
// "generateConstructorInterface": true,
// "convertConstructorInterfaceData": false,
// "importRequiredTypes": true,
// "useGetBaseUrlMethod": false,
// "baseUrlTokenName": "API_BASE_URL",
// "queryNullValue": "",
// "useAbortSignal": false,
// "inlineNamedDictionaries": false,
// "inlineNamedAny": false,
// "includeHttpContext": false,
// "templateDirectory": null,
// "typeNameGeneratorType": null,
// "propertyNameGeneratorType": null,
// "enumNameGeneratorType": null,
// "serviceHost": null,
// "serviceSchemes": null,
// "output": "ClientApp/src/app/web-api-client.ts",
// "newLineBehavior": "Auto"
// }
//}
}

0 comments on commit dbea518

Please sign in to comment.