From 5d899f612077faa460bb0d75bd26a8b4ce505999 Mon Sep 17 00:00:00 2001 From: raffael Date: Thu, 19 Oct 2017 09:43:44 +0200 Subject: [PATCH 1/9] add support for async routes/endpoints you can now set --optional-properties async=true to generate a nancyfx server stub that uses asynchronous programming. (cherry picked from commit 126869cb0b967e8063417e11993cf6326ce8ffd4) --- .../codegen/languages/NancyFXServerCodegen.java | 2 ++ .../src/main/resources/nancyfx/api.mustache | 13 +++++++------ samples/server/petstore/nancyfx/IO.Swagger.sln | 10 +++++----- .../nancyfx/src/IO.Swagger/IO.Swagger.csproj | 2 +- .../nancyfx/src/IO.Swagger/Modules/PetModule.cs | 1 + .../nancyfx/src/IO.Swagger/Modules/StoreModule.cs | 1 + .../nancyfx/src/IO.Swagger/Modules/UserModule.cs | 1 + 7 files changed, 18 insertions(+), 12 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java index 5e577b4c3de..2a3ff4a096b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java @@ -46,6 +46,7 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { private static final String IMMUTABLE_OPTION = "immutable"; private static final String USE_BASE_PATH = "writeModulePath"; private static final String PACKAGE_CONTEXT = "packageContext"; + private static final String ASYNC = "async"; private static final Map> propertyToSwaggerTypeMapping = createPropertyToSwaggerTypeMapping(); @@ -78,6 +79,7 @@ public NancyFXServerCodegen() { addOption(INTERFACE_PREFIX, INTERFACE_PREFIX_DESC, interfacePrefix); addOption(OPTIONAL_PROJECT_GUID,OPTIONAL_PROJECT_GUID_DESC, null); addOption(PACKAGE_CONTEXT, "Optionally overrides the PackageContext which determines the namespace (namespace=packageName.packageContext). If not set, packageContext will default to basePath.", null); + addOption(ASYNC, "Set to true to enable the generation of async routes.", "false"); // CLI Switches addSwitch(SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_BY_REQUIRED_FLAG_DESC, sortParamsByRequiredFlag); diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache index 038977fb6d4..0a9ef48f91c 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache @@ -6,6 +6,7 @@ using Sharpility.Base; using {{packageName}}.{{packageContext}}.Models; using {{packageName}}.{{packageContext}}.Utils; using NodaTime; +{{#async}}using System.Threading.Tasks;{{/async}} {{#imports}}using {{import}}; {{/imports}} @@ -24,13 +25,13 @@ namespace {{packageName}}.{{packageContext}}.Modules /// Service handling requests public {{classname}}Module({{interfacePrefix}}{{classname}}Service service) : base("{{{baseContext}}}") { {{#operation}} - {{httpMethod}}["{{{path}}}"] = parameters => + {{httpMethod}}["{{{path}}}"{{#async}}, true{{/async}}] = {{#async}}async (parameters, ct){{/async}}{{^async}}parameters{{/async}} => { {{#allParams}}{{#isBodyParam}}var {{paramName}} = this.Bind<{{&dataType}}>();{{/isBodyParam}}{{^isBodyParam}}{{#isEnum}}var {{paramName}} = Parameters.ValueOf<{{>innerApiEnumName}}?>({{>innerParameterValueOfArgs}});{{/isEnum}}{{^isEnum}}var {{paramName}} = Parameters.ValueOf<{{&dataType}}>({{>innerParameterValueOfArgs}});{{/isEnum}}{{#hasMore}} {{/hasMore}}{{/isBodyParam}}{{/allParams}}{{#allParams}}{{#required}} Preconditions.IsNotNull({{paramName}}, "Required parameter: '{{paramName}}' is missing at '{{operationId}}'"); {{/required}}{{/allParams}} - {{#returnType}}return {{/returnType}}service.{{operationId}}(Context{{#allParams.0}}, {{/allParams.0}}{{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}{{#isListContainer}}.ToArray(){{/isListContainer}}{{/returnType}};{{^returnType}} + {{#returnType}}return {{/returnType}}{{^returnType}}{{#async}}await {{/async}}{{/returnType}}service.{{operationId}}(Context{{#allParams.0}}, {{/allParams.0}}{{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}{{#isListContainer}}.ToArray(){{/isListContainer}}{{/returnType}};{{^returnType}} return new Response { ContentType = "{{produces.0.mediaType}}"};{{/returnType}} }; {{/operation}} @@ -48,7 +49,7 @@ namespace {{packageName}}.{{packageContext}}.Modules /// Context of request {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} - {{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}});{{#hasMore}} + {{#async}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/async}}{{^async}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/async}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}});{{#hasMore}} {{/hasMore}}{{/operation}} } @@ -58,14 +59,14 @@ namespace {{packageName}}.{{packageContext}}.Modules /// public abstract class Abstract{{classname}}Service: {{interfacePrefix}}{{classname}}Service { - {{#operation}}public virtual {{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}}) + {{#operation}}public virtual {{#async}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/async}}{{^async}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/async}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}}) { - {{#returnType}}return {{/returnType}}{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{^async}}{{#returnType}}return {{/returnType}}{{/async}}{{#async}}return {{/async}}{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); }{{#hasMore}} {{/hasMore}}{{/operation}} - {{#operation}}protected abstract {{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{>paramsList}});{{#hasMore}} + {{#operation}}protected abstract {{#async}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/async}}{{^async}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/async}} {{operationId}}({{>paramsList}});{{#hasMore}} {{/hasMore}}{{/operation}} } diff --git a/samples/server/petstore/nancyfx/IO.Swagger.sln b/samples/server/petstore/nancyfx/IO.Swagger.sln index 680fe56caa0..b17b1c49583 100644 --- a/samples/server/petstore/nancyfx/IO.Swagger.sln +++ b/samples/server/petstore/nancyfx/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{19B8107D-38E2-4D32-B74F-C45470A9FCA3}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{CA250BF8-2025-4976-8E5A-10668D3F3D22}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -10,10 +10,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{DFBD27E3-36EF-45CB-9D6D-EF500915B5CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{DFBD27E3-36EF-45CB-9D6D-EF500915B5CF}.Debug|Any CPU.Build.0 = Debug|Any CPU -{DFBD27E3-36EF-45CB-9D6D-EF500915B5CF}.Release|Any CPU.ActiveCfg = Release|Any CPU -{DFBD27E3-36EF-45CB-9D6D-EF500915B5CF}.Release|Any CPU.Build.0 = Release|Any CPU +{CA250BF8-2025-4976-8E5A-10668D3F3D22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{CA250BF8-2025-4976-8E5A-10668D3F3D22}.Debug|Any CPU.Build.0 = Debug|Any CPU +{CA250BF8-2025-4976-8E5A-10668D3F3D22}.Release|Any CPU.ActiveCfg = Release|Any CPU +{CA250BF8-2025-4976-8E5A-10668D3F3D22}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj index b7bb26dd9df..79c47a207b3 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj @@ -3,7 +3,7 @@ Debug AnyCPU - {19B8107D-38E2-4D32-B74F-C45470A9FCA3} + {CA250BF8-2025-4976-8E5A-10668D3F3D22} Library Properties IO.Swagger.v2 diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs index edfa0ecac4a..f27290da30b 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs @@ -7,6 +7,7 @@ using IO.Swagger.v2.Utils; using NodaTime; + namespace IO.Swagger.v2.Modules { /// diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs index e5eed7a2485..17525f5c6bb 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs @@ -7,6 +7,7 @@ using IO.Swagger.v2.Utils; using NodaTime; + namespace IO.Swagger.v2.Modules { diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs index 978013f17bb..3abe9a8fc14 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs @@ -7,6 +7,7 @@ using IO.Swagger.v2.Utils; using NodaTime; + namespace IO.Swagger.v2.Modules { From 4fbe701de73b56330f3f19570730e18127d33c61 Mon Sep 17 00:00:00 2001 From: raffael Date: Thu, 19 Oct 2017 14:49:40 +0200 Subject: [PATCH 2/9] add nancyfx-petstore-server-async.sh to generate sample of async nancyfx. --- bin/nancyfx-petstore-server-async.sh | 31 ++ .../nancyfx-async/.swagger-codegen-ignore | 23 + .../nancyfx-async/.swagger-codegen/VERSION | 1 + .../petstore/nancyfx-async/IO.Swagger.sln | 25 + .../src/IO.Swagger/IO.Swagger.csproj | 66 +++ .../src/IO.Swagger/IO.Swagger.nuspec | 14 + .../src/IO.Swagger/Models/ApiResponse.cs | 185 ++++++++ .../src/IO.Swagger/Models/Category.cs | 165 +++++++ .../src/IO.Swagger/Models/Order.cs | 247 ++++++++++ .../src/IO.Swagger/Models/Pet.cs | 254 ++++++++++ .../src/IO.Swagger/Models/Tag.cs | 165 +++++++ .../src/IO.Swagger/Models/User.cs | 285 +++++++++++ .../src/IO.Swagger/Modules/PetModule.cs | 247 ++++++++++ .../src/IO.Swagger/Modules/StoreModule.cs | 129 +++++ .../src/IO.Swagger/Modules/UserModule.cs | 234 +++++++++ .../src/IO.Swagger/Utils/Parameters.cs | 443 ++++++++++++++++++ .../src/IO.Swagger/packages.config | 7 + .../server/petstore/nancyfx/IO.Swagger.sln | 10 +- .../nancyfx/src/IO.Swagger/IO.Swagger.csproj | 2 +- 19 files changed, 2527 insertions(+), 6 deletions(-) create mode 100644 bin/nancyfx-petstore-server-async.sh create mode 100644 samples/server/petstore/nancyfx-async/.swagger-codegen-ignore create mode 100644 samples/server/petstore/nancyfx-async/.swagger-codegen/VERSION create mode 100644 samples/server/petstore/nancyfx-async/IO.Swagger.sln create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.csproj create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.nuspec create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/ApiResponse.cs create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Category.cs create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Order.cs create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Pet.cs create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Tag.cs create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/User.cs create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/Parameters.cs create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/packages.config diff --git a/bin/nancyfx-petstore-server-async.sh b/bin/nancyfx-petstore-server-async.sh new file mode 100644 index 00000000000..e5198c4fc1b --- /dev/null +++ b/bin/nancyfx-petstore-server-async.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate $@ -t modules/swagger-codegen/src/main/resources/nancyfx -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nancyfx -o samples/server/petstore/nancyfx-async --additional-properties packageGuid={768B8DC6-54EE-4D40-9B20-7857E1D742A4},async=true" + +java $JAVA_OPTS -jar $executable $ags diff --git a/samples/server/petstore/nancyfx-async/.swagger-codegen-ignore b/samples/server/petstore/nancyfx-async/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/nancyfx-async/.swagger-codegen/VERSION b/samples/server/petstore/nancyfx-async/.swagger-codegen/VERSION new file mode 100644 index 00000000000..f9f7450d135 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/IO.Swagger.sln b/samples/server/petstore/nancyfx-async/IO.Swagger.sln new file mode 100644 index 00000000000..1e40deb1a14 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/IO.Swagger.sln @@ -0,0 +1,25 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +VisualStudioVersion = 12.0.0.0 +MinimumVisualStudioVersion = 10.0.0.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{768B8DC6-54EE-4D40-9B20-7857E1D742A4}" +EndProject +Global +GlobalSection(SolutionConfigurationPlatforms) = preSolution +Debug|Any CPU = Debug|Any CPU +Release|Any CPU = Release|Any CPU +EndGlobalSection +GlobalSection(ProjectConfigurationPlatforms) = postSolution +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Debug|Any CPU.Build.0 = Debug|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Release|Any CPU.ActiveCfg = Release|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Release|Any CPU.Build.0 = Release|Any CPU +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU +EndGlobalSection +GlobalSection(SolutionProperties) = preSolution +HideSolutionNode = FALSE +EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.csproj b/samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.csproj new file mode 100644 index 00000000000..e1577197b6f --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.csproj @@ -0,0 +1,66 @@ + + + + Debug + AnyCPU + {768B8DC6-54EE-4D40-9B20-7857E1D742A4} + Library + Properties + IO.Swagger.v2 + IO.Swagger + v4.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + bin\Debug\IO.Swagger.XML + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + bin\Release\IO.Swagger.XML + + + + ..\..\packages\Nancy.1.4.3\lib\net40\Nancy.dll + True + + + ..\..\packages\NodaTime.1.3.1\lib\net35-Client\NodaTime.dll + True + + + ..\..\packages\Sharpility.1.2.2\lib\net45\Sharpility.dll + True + + + ..\..\packages\System.Collections.Immutable.1.1.37\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll + True + + + + + + + + + + + + + + + + + + diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.nuspec b/samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.nuspec new file mode 100644 index 00000000000..889fe96ab03 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/IO.Swagger.nuspec @@ -0,0 +1,14 @@ + + + + IO.Swagger + IO.Swagger + 1.0.0 + swagger-codegen + swagger-codegen + false + NancyFx IO.Swagger API + http://swagger.io/terms/ + http://www.apache.org/licenses/LICENSE-2.0.html + + \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/ApiResponse.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/ApiResponse.cs new file mode 100644 index 00000000000..ebaa3c8d4f1 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/ApiResponse.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + /// + /// Describes the result of uploading an image resource + /// + public sealed class ApiResponse: IEquatable + { + /// + /// Code + /// + public int? Code { get; private set; } + + /// + /// Type + /// + public string Type { get; private set; } + + /// + /// Message + /// + public string Message { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use ApiResponse.Builder() for instance creation instead. + /// + [Obsolete] + public ApiResponse() + { + } + + private ApiResponse(int? Code, string Type, string Message) + { + + this.Code = Code; + + this.Type = Type; + + this.Message = Message; + + } + + /// + /// Returns builder of ApiResponse. + /// + /// ApiResponseBuilder + public static ApiResponseBuilder Builder() + { + return new ApiResponseBuilder(); + } + + /// + /// Returns ApiResponseBuilder with properties set. + /// Use it to change properties. + /// + /// ApiResponseBuilder + public ApiResponseBuilder With() + { + return Builder() + .Code(Code) + .Type(Type) + .Message(Message); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(ApiResponse other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (ApiResponse. + /// + /// Compared (ApiResponse + /// Compared (ApiResponse + /// true if compared items are equals, false otherwise + public static bool operator == (ApiResponse left, ApiResponse right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (ApiResponse. + /// + /// Compared (ApiResponse + /// Compared (ApiResponse + /// true if compared items are not equals, false otherwise + public static bool operator != (ApiResponse left, ApiResponse right) + { + return !Equals(left, right); + } + + /// + /// Builder of ApiResponse. + /// + public sealed class ApiResponseBuilder + { + private int? _Code; + private string _Type; + private string _Message; + + internal ApiResponseBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + } + + /// + /// Sets value for ApiResponse.Code property. + /// + /// Code + public ApiResponseBuilder Code(int? value) + { + _Code = value; + return this; + } + + /// + /// Sets value for ApiResponse.Type property. + /// + /// Type + public ApiResponseBuilder Type(string value) + { + _Type = value; + return this; + } + + /// + /// Sets value for ApiResponse.Message property. + /// + /// Message + public ApiResponseBuilder Message(string value) + { + _Message = value; + return this; + } + + + /// + /// Builds instance of ApiResponse. + /// + /// ApiResponse + public ApiResponse Build() + { + Validate(); + return new ApiResponse( + Code: _Code, + Type: _Type, + Message: _Message + ); + } + + private void Validate() + { + } + } + + + } +} \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Category.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Category.cs new file mode 100644 index 00000000000..bf811614b37 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Category.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + /// + /// A category for a pet + /// + public sealed class Category: IEquatable + { + /// + /// Id + /// + public long? Id { get; private set; } + + /// + /// Name + /// + public string Name { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use Category.Builder() for instance creation instead. + /// + [Obsolete] + public Category() + { + } + + private Category(long? Id, string Name) + { + + this.Id = Id; + + this.Name = Name; + + } + + /// + /// Returns builder of Category. + /// + /// CategoryBuilder + public static CategoryBuilder Builder() + { + return new CategoryBuilder(); + } + + /// + /// Returns CategoryBuilder with properties set. + /// Use it to change properties. + /// + /// CategoryBuilder + public CategoryBuilder With() + { + return Builder() + .Id(Id) + .Name(Name); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(Category other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (Category. + /// + /// Compared (Category + /// Compared (Category + /// true if compared items are equals, false otherwise + public static bool operator == (Category left, Category right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (Category. + /// + /// Compared (Category + /// Compared (Category + /// true if compared items are not equals, false otherwise + public static bool operator != (Category left, Category right) + { + return !Equals(left, right); + } + + /// + /// Builder of Category. + /// + public sealed class CategoryBuilder + { + private long? _Id; + private string _Name; + + internal CategoryBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + } + + /// + /// Sets value for Category.Id property. + /// + /// Id + public CategoryBuilder Id(long? value) + { + _Id = value; + return this; + } + + /// + /// Sets value for Category.Name property. + /// + /// Name + public CategoryBuilder Name(string value) + { + _Name = value; + return this; + } + + + /// + /// Builds instance of Category. + /// + /// Category + public Category Build() + { + Validate(); + return new Category( + Id: _Id, + Name: _Name + ); + } + + private void Validate() + { + } + } + + + } +} \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Order.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Order.cs new file mode 100644 index 00000000000..0495a36f138 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Order.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + /// + /// An order for a pets from the pet store + /// + public sealed class Order: IEquatable + { + /// + /// Id + /// + public long? Id { get; private set; } + + /// + /// PetId + /// + public long? PetId { get; private set; } + + /// + /// Quantity + /// + public int? Quantity { get; private set; } + + /// + /// ShipDate + /// + public ZonedDateTime? ShipDate { get; private set; } + + /// + /// Order Status + /// + public StatusEnum? Status { get; private set; } + + /// + /// Complete + /// + public bool? Complete { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use Order.Builder() for instance creation instead. + /// + [Obsolete] + public Order() + { + } + + private Order(long? Id, long? PetId, int? Quantity, ZonedDateTime? ShipDate, StatusEnum? Status, bool? Complete) + { + + this.Id = Id; + + this.PetId = PetId; + + this.Quantity = Quantity; + + this.ShipDate = ShipDate; + + this.Status = Status; + + this.Complete = Complete; + + } + + /// + /// Returns builder of Order. + /// + /// OrderBuilder + public static OrderBuilder Builder() + { + return new OrderBuilder(); + } + + /// + /// Returns OrderBuilder with properties set. + /// Use it to change properties. + /// + /// OrderBuilder + public OrderBuilder With() + { + return Builder() + .Id(Id) + .PetId(PetId) + .Quantity(Quantity) + .ShipDate(ShipDate) + .Status(Status) + .Complete(Complete); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(Order other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (Order. + /// + /// Compared (Order + /// Compared (Order + /// true if compared items are equals, false otherwise + public static bool operator == (Order left, Order right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (Order. + /// + /// Compared (Order + /// Compared (Order + /// true if compared items are not equals, false otherwise + public static bool operator != (Order left, Order right) + { + return !Equals(left, right); + } + + /// + /// Builder of Order. + /// + public sealed class OrderBuilder + { + private long? _Id; + private long? _PetId; + private int? _Quantity; + private ZonedDateTime? _ShipDate; + private StatusEnum? _Status; + private bool? _Complete; + + internal OrderBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + _Complete = false; + } + + /// + /// Sets value for Order.Id property. + /// + /// Id + public OrderBuilder Id(long? value) + { + _Id = value; + return this; + } + + /// + /// Sets value for Order.PetId property. + /// + /// PetId + public OrderBuilder PetId(long? value) + { + _PetId = value; + return this; + } + + /// + /// Sets value for Order.Quantity property. + /// + /// Quantity + public OrderBuilder Quantity(int? value) + { + _Quantity = value; + return this; + } + + /// + /// Sets value for Order.ShipDate property. + /// + /// ShipDate + public OrderBuilder ShipDate(ZonedDateTime? value) + { + _ShipDate = value; + return this; + } + + /// + /// Sets value for Order.Status property. + /// + /// Order Status + public OrderBuilder Status(StatusEnum? value) + { + _Status = value; + return this; + } + + /// + /// Sets value for Order.Complete property. + /// + /// Complete + public OrderBuilder Complete(bool? value) + { + _Complete = value; + return this; + } + + + /// + /// Builds instance of Order. + /// + /// Order + public Order Build() + { + Validate(); + return new Order( + Id: _Id, + PetId: _PetId, + Quantity: _Quantity, + ShipDate: _ShipDate, + Status: _Status, + Complete: _Complete + ); + } + + private void Validate() + { + } + } + + + public enum StatusEnum { Placed, Approved, Delivered }; + } +} \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Pet.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Pet.cs new file mode 100644 index 00000000000..f945a0fdd78 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Pet.cs @@ -0,0 +1,254 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + /// + /// A pet for sale in the pet store + /// + public sealed class Pet: IEquatable + { + /// + /// Id + /// + public long? Id { get; private set; } + + /// + /// Category + /// + public Category Category { get; private set; } + + /// + /// Name + /// + public string Name { get; private set; } + + /// + /// PhotoUrls + /// + public List PhotoUrls { get; private set; } + + /// + /// Tags + /// + public List Tags { get; private set; } + + /// + /// pet status in the store + /// + public StatusEnum? Status { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use Pet.Builder() for instance creation instead. + /// + [Obsolete] + public Pet() + { + } + + private Pet(long? Id, Category Category, string Name, List PhotoUrls, List Tags, StatusEnum? Status) + { + + this.Id = Id; + + this.Category = Category; + + this.Name = Name; + + this.PhotoUrls = PhotoUrls; + + this.Tags = Tags; + + this.Status = Status; + + } + + /// + /// Returns builder of Pet. + /// + /// PetBuilder + public static PetBuilder Builder() + { + return new PetBuilder(); + } + + /// + /// Returns PetBuilder with properties set. + /// Use it to change properties. + /// + /// PetBuilder + public PetBuilder With() + { + return Builder() + .Id(Id) + .Category(Category) + .Name(Name) + .PhotoUrls(PhotoUrls) + .Tags(Tags) + .Status(Status); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(Pet other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (Pet. + /// + /// Compared (Pet + /// Compared (Pet + /// true if compared items are equals, false otherwise + public static bool operator == (Pet left, Pet right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (Pet. + /// + /// Compared (Pet + /// Compared (Pet + /// true if compared items are not equals, false otherwise + public static bool operator != (Pet left, Pet right) + { + return !Equals(left, right); + } + + /// + /// Builder of Pet. + /// + public sealed class PetBuilder + { + private long? _Id; + private Category _Category; + private string _Name; + private List _PhotoUrls; + private List _Tags; + private StatusEnum? _Status; + + internal PetBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + } + + /// + /// Sets value for Pet.Id property. + /// + /// Id + public PetBuilder Id(long? value) + { + _Id = value; + return this; + } + + /// + /// Sets value for Pet.Category property. + /// + /// Category + public PetBuilder Category(Category value) + { + _Category = value; + return this; + } + + /// + /// Sets value for Pet.Name property. + /// + /// Name + public PetBuilder Name(string value) + { + _Name = value; + return this; + } + + /// + /// Sets value for Pet.PhotoUrls property. + /// + /// PhotoUrls + public PetBuilder PhotoUrls(List value) + { + _PhotoUrls = value; + return this; + } + + /// + /// Sets value for Pet.Tags property. + /// + /// Tags + public PetBuilder Tags(List value) + { + _Tags = value; + return this; + } + + /// + /// Sets value for Pet.Status property. + /// + /// pet status in the store + public PetBuilder Status(StatusEnum? value) + { + _Status = value; + return this; + } + + + /// + /// Builds instance of Pet. + /// + /// Pet + public Pet Build() + { + Validate(); + return new Pet( + Id: _Id, + Category: _Category, + Name: _Name, + PhotoUrls: _PhotoUrls, + Tags: _Tags, + Status: _Status + ); + } + + private void Validate() + { + if (_Name == null) + { + throw new ArgumentException("Name is a required property for Pet and cannot be null"); + } + if (_PhotoUrls == null) + { + throw new ArgumentException("PhotoUrls is a required property for Pet and cannot be null"); + } + } + } + + + public enum StatusEnum { Available, Pending, Sold }; + } +} \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Tag.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Tag.cs new file mode 100644 index 00000000000..02d1e40f1ec --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/Tag.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + /// + /// A tag for a pet + /// + public sealed class Tag: IEquatable + { + /// + /// Id + /// + public long? Id { get; private set; } + + /// + /// Name + /// + public string Name { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use Tag.Builder() for instance creation instead. + /// + [Obsolete] + public Tag() + { + } + + private Tag(long? Id, string Name) + { + + this.Id = Id; + + this.Name = Name; + + } + + /// + /// Returns builder of Tag. + /// + /// TagBuilder + public static TagBuilder Builder() + { + return new TagBuilder(); + } + + /// + /// Returns TagBuilder with properties set. + /// Use it to change properties. + /// + /// TagBuilder + public TagBuilder With() + { + return Builder() + .Id(Id) + .Name(Name); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(Tag other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (Tag. + /// + /// Compared (Tag + /// Compared (Tag + /// true if compared items are equals, false otherwise + public static bool operator == (Tag left, Tag right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (Tag. + /// + /// Compared (Tag + /// Compared (Tag + /// true if compared items are not equals, false otherwise + public static bool operator != (Tag left, Tag right) + { + return !Equals(left, right); + } + + /// + /// Builder of Tag. + /// + public sealed class TagBuilder + { + private long? _Id; + private string _Name; + + internal TagBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + } + + /// + /// Sets value for Tag.Id property. + /// + /// Id + public TagBuilder Id(long? value) + { + _Id = value; + return this; + } + + /// + /// Sets value for Tag.Name property. + /// + /// Name + public TagBuilder Name(string value) + { + _Name = value; + return this; + } + + + /// + /// Builds instance of Tag. + /// + /// Tag + public Tag Build() + { + Validate(); + return new Tag( + Id: _Id, + Name: _Name + ); + } + + private void Validate() + { + } + } + + + } +} \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/User.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/User.cs new file mode 100644 index 00000000000..99f401750df --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Models/User.cs @@ -0,0 +1,285 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + /// + /// A User who is purchasing from the pet store + /// + public sealed class User: IEquatable + { + /// + /// Id + /// + public long? Id { get; private set; } + + /// + /// Username + /// + public string Username { get; private set; } + + /// + /// FirstName + /// + public string FirstName { get; private set; } + + /// + /// LastName + /// + public string LastName { get; private set; } + + /// + /// Email + /// + public string Email { get; private set; } + + /// + /// Password + /// + public string Password { get; private set; } + + /// + /// Phone + /// + public string Phone { get; private set; } + + /// + /// User Status + /// + public int? UserStatus { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use User.Builder() for instance creation instead. + /// + [Obsolete] + public User() + { + } + + private User(long? Id, string Username, string FirstName, string LastName, string Email, string Password, string Phone, int? UserStatus) + { + + this.Id = Id; + + this.Username = Username; + + this.FirstName = FirstName; + + this.LastName = LastName; + + this.Email = Email; + + this.Password = Password; + + this.Phone = Phone; + + this.UserStatus = UserStatus; + + } + + /// + /// Returns builder of User. + /// + /// UserBuilder + public static UserBuilder Builder() + { + return new UserBuilder(); + } + + /// + /// Returns UserBuilder with properties set. + /// Use it to change properties. + /// + /// UserBuilder + public UserBuilder With() + { + return Builder() + .Id(Id) + .Username(Username) + .FirstName(FirstName) + .LastName(LastName) + .Email(Email) + .Password(Password) + .Phone(Phone) + .UserStatus(UserStatus); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(User other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (User. + /// + /// Compared (User + /// Compared (User + /// true if compared items are equals, false otherwise + public static bool operator == (User left, User right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (User. + /// + /// Compared (User + /// Compared (User + /// true if compared items are not equals, false otherwise + public static bool operator != (User left, User right) + { + return !Equals(left, right); + } + + /// + /// Builder of User. + /// + public sealed class UserBuilder + { + private long? _Id; + private string _Username; + private string _FirstName; + private string _LastName; + private string _Email; + private string _Password; + private string _Phone; + private int? _UserStatus; + + internal UserBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + } + + /// + /// Sets value for User.Id property. + /// + /// Id + public UserBuilder Id(long? value) + { + _Id = value; + return this; + } + + /// + /// Sets value for User.Username property. + /// + /// Username + public UserBuilder Username(string value) + { + _Username = value; + return this; + } + + /// + /// Sets value for User.FirstName property. + /// + /// FirstName + public UserBuilder FirstName(string value) + { + _FirstName = value; + return this; + } + + /// + /// Sets value for User.LastName property. + /// + /// LastName + public UserBuilder LastName(string value) + { + _LastName = value; + return this; + } + + /// + /// Sets value for User.Email property. + /// + /// Email + public UserBuilder Email(string value) + { + _Email = value; + return this; + } + + /// + /// Sets value for User.Password property. + /// + /// Password + public UserBuilder Password(string value) + { + _Password = value; + return this; + } + + /// + /// Sets value for User.Phone property. + /// + /// Phone + public UserBuilder Phone(string value) + { + _Phone = value; + return this; + } + + /// + /// Sets value for User.UserStatus property. + /// + /// User Status + public UserBuilder UserStatus(int? value) + { + _UserStatus = value; + return this; + } + + + /// + /// Builds instance of User. + /// + /// User + public User Build() + { + Validate(); + return new User( + Id: _Id, + Username: _Username, + FirstName: _FirstName, + LastName: _LastName, + Email: _Email, + Password: _Password, + Phone: _Phone, + UserStatus: _UserStatus + ); + } + + private void Validate() + { + } + } + + + } +} \ No newline at end of file diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs new file mode 100644 index 00000000000..27841e5c662 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs @@ -0,0 +1,247 @@ +using System; +using Nancy; +using Nancy.ModelBinding; +using System.Collections.Generic; +using Sharpility.Base; +using IO.Swagger.v2.Models; +using IO.Swagger.v2.Utils; +using NodaTime; +using System.Threading.Tasks; + +namespace IO.Swagger.v2.Modules +{ + /// + /// Status values that need to be considered for filter + /// + public enum FindPetsByStatusStatusEnum + { + available, + pending, + sold + }; + + + /// + /// Module processing requests of Pet domain. + /// + public sealed class PetModule : NancyModule + { + /// + /// Sets up HTTP methods mappings. + /// + /// Service handling requests + public PetModule(PetService service) : base("/v2") + { + Post["/pet", true] = async (parameters, ct) => + { + var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'AddPet'"); + + await service.AddPet(Context, body); + return new Response { ContentType = "application/xml"}; + }; + + Delete["/pet/{petId}", true] = async (parameters, ct) => + { + var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); + var apiKey = Parameters.ValueOf(parameters, Context.Request, "apiKey", ParameterType.Header); + Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'DeletePet'"); + + await service.DeletePet(Context, petId, apiKey); + return new Response { ContentType = "application/xml"}; + }; + + Get["/pet/findByStatus", true] = async (parameters, ct) => + { + var status = Parameters.ValueOf(parameters, Context.Request, "status", ParameterType.Query); + Preconditions.IsNotNull(status, "Required parameter: 'status' is missing at 'FindPetsByStatus'"); + + return service.FindPetsByStatus(Context, status).ToArray(); + }; + + Get["/pet/findByTags", true] = async (parameters, ct) => + { + var tags = Parameters.ValueOf>(parameters, Context.Request, "tags", ParameterType.Query); + Preconditions.IsNotNull(tags, "Required parameter: 'tags' is missing at 'FindPetsByTags'"); + + return service.FindPetsByTags(Context, tags).ToArray(); + }; + + Get["/pet/{petId}", true] = async (parameters, ct) => + { + var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); + Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'GetPetById'"); + + return service.GetPetById(Context, petId); + }; + + Put["/pet", true] = async (parameters, ct) => + { + var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdatePet'"); + + await service.UpdatePet(Context, body); + return new Response { ContentType = "application/xml"}; + }; + + Post["/pet/{petId}", true] = async (parameters, ct) => + { + var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); + var name = Parameters.ValueOf(parameters, Context.Request, "name", ParameterType.Undefined); + var status = Parameters.ValueOf(parameters, Context.Request, "status", ParameterType.Undefined); + Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UpdatePetWithForm'"); + + await service.UpdatePetWithForm(Context, petId, name, status); + return new Response { ContentType = "application/xml"}; + }; + + Post["/pet/{petId}/uploadImage", true] = async (parameters, ct) => + { + var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); + var additionalMetadata = Parameters.ValueOf(parameters, Context.Request, "additionalMetadata", ParameterType.Undefined); + var file = Parameters.ValueOf(parameters, Context.Request, "file", ParameterType.Undefined); + Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UploadFile'"); + + return service.UploadFile(Context, petId, additionalMetadata, file); + }; + } + } + + /// + /// Service handling Pet requests. + /// + public interface PetService + { + /// + /// + /// + /// Context of request + /// Pet object that needs to be added to the store + /// + Task AddPet(NancyContext context, Pet body); + + /// + /// + /// + /// Context of request + /// Pet id to delete + /// (optional) + /// + Task DeletePet(NancyContext context, long? petId, string apiKey); + + /// + /// Multiple status values can be provided with comma separated strings + /// + /// Context of request + /// Status values that need to be considered for filter + /// List<Pet> + Task> FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status); + + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Context of request + /// Tags to filter by + /// List<Pet> + Task> FindPetsByTags(NancyContext context, List tags); + + /// + /// Returns a single pet + /// + /// Context of request + /// ID of pet to return + /// Pet + Task GetPetById(NancyContext context, long? petId); + + /// + /// + /// + /// Context of request + /// Pet object that needs to be added to the store + /// + Task UpdatePet(NancyContext context, Pet body); + + /// + /// + /// + /// Context of request + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// + Task UpdatePetWithForm(NancyContext context, long? petId, string name, string status); + + /// + /// + /// + /// Context of request + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// ApiResponse + Task UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file); + } + + /// + /// Abstraction of PetService. + /// + public abstract class AbstractPetService: PetService + { + public virtual Task AddPet(NancyContext context, Pet body) + { + return AddPet(body); + } + + public virtual Task DeletePet(NancyContext context, long? petId, string apiKey) + { + return DeletePet(petId, apiKey); + } + + public virtual Task> FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status) + { + return FindPetsByStatus(status); + } + + public virtual Task> FindPetsByTags(NancyContext context, List tags) + { + return FindPetsByTags(tags); + } + + public virtual Task GetPetById(NancyContext context, long? petId) + { + return GetPetById(petId); + } + + public virtual Task UpdatePet(NancyContext context, Pet body) + { + return UpdatePet(body); + } + + public virtual Task UpdatePetWithForm(NancyContext context, long? petId, string name, string status) + { + return UpdatePetWithForm(petId, name, status); + } + + public virtual Task UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file) + { + return UploadFile(petId, additionalMetadata, file); + } + + protected abstract Task AddPet(Pet body); + + protected abstract Task DeletePet(long? petId, string apiKey); + + protected abstract Task> FindPetsByStatus(FindPetsByStatusStatusEnum? status); + + protected abstract Task> FindPetsByTags(List tags); + + protected abstract Task GetPetById(long? petId); + + protected abstract Task UpdatePet(Pet body); + + protected abstract Task UpdatePetWithForm(long? petId, string name, string status); + + protected abstract Task UploadFile(long? petId, string additionalMetadata, System.IO.Stream file); + } + +} diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs new file mode 100644 index 00000000000..b494e8a4e74 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs @@ -0,0 +1,129 @@ +using System; +using Nancy; +using Nancy.ModelBinding; +using System.Collections.Generic; +using Sharpility.Base; +using IO.Swagger.v2.Models; +using IO.Swagger.v2.Utils; +using NodaTime; +using System.Threading.Tasks; + +namespace IO.Swagger.v2.Modules +{ + + /// + /// Module processing requests of Store domain. + /// + public sealed class StoreModule : NancyModule + { + /// + /// Sets up HTTP methods mappings. + /// + /// Service handling requests + public StoreModule(StoreService service) : base("/v2") + { + Delete["/store/order/{orderId}", true] = async (parameters, ct) => + { + var orderId = Parameters.ValueOf(parameters, Context.Request, "orderId", ParameterType.Path); + Preconditions.IsNotNull(orderId, "Required parameter: 'orderId' is missing at 'DeleteOrder'"); + + await service.DeleteOrder(Context, orderId); + return new Response { ContentType = "application/xml"}; + }; + + Get["/store/inventory", true] = async (parameters, ct) => + { + + return service.GetInventory(Context); + }; + + Get["/store/order/{orderId}", true] = async (parameters, ct) => + { + var orderId = Parameters.ValueOf(parameters, Context.Request, "orderId", ParameterType.Path); + Preconditions.IsNotNull(orderId, "Required parameter: 'orderId' is missing at 'GetOrderById'"); + + return service.GetOrderById(Context, orderId); + }; + + Post["/store/order", true] = async (parameters, ct) => + { + var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'PlaceOrder'"); + + return service.PlaceOrder(Context, body); + }; + } + } + + /// + /// Service handling Store requests. + /// + public interface StoreService + { + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Context of request + /// ID of the order that needs to be deleted + /// + Task DeleteOrder(NancyContext context, string orderId); + + /// + /// Returns a map of status codes to quantities + /// + /// Context of request + /// Dictionary<string, int?> + Task> GetInventory(NancyContext context); + + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Context of request + /// ID of pet that needs to be fetched + /// Order + Task GetOrderById(NancyContext context, long? orderId); + + /// + /// + /// + /// Context of request + /// order placed for purchasing the pet + /// Order + Task PlaceOrder(NancyContext context, Order body); + } + + /// + /// Abstraction of StoreService. + /// + public abstract class AbstractStoreService: StoreService + { + public virtual Task DeleteOrder(NancyContext context, string orderId) + { + return DeleteOrder(orderId); + } + + public virtual Task> GetInventory(NancyContext context) + { + return GetInventory(); + } + + public virtual Task GetOrderById(NancyContext context, long? orderId) + { + return GetOrderById(orderId); + } + + public virtual Task PlaceOrder(NancyContext context, Order body) + { + return PlaceOrder(body); + } + + protected abstract Task DeleteOrder(string orderId); + + protected abstract Task> GetInventory(); + + protected abstract Task GetOrderById(long? orderId); + + protected abstract Task PlaceOrder(Order body); + } + +} diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs new file mode 100644 index 00000000000..bba288d82e7 --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs @@ -0,0 +1,234 @@ +using System; +using Nancy; +using Nancy.ModelBinding; +using System.Collections.Generic; +using Sharpility.Base; +using IO.Swagger.v2.Models; +using IO.Swagger.v2.Utils; +using NodaTime; +using System.Threading.Tasks; + +namespace IO.Swagger.v2.Modules +{ + + /// + /// Module processing requests of User domain. + /// + public sealed class UserModule : NancyModule + { + /// + /// Sets up HTTP methods mappings. + /// + /// Service handling requests + public UserModule(UserService service) : base("/v2") + { + Post["/user", true] = async (parameters, ct) => + { + var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUser'"); + + await service.CreateUser(Context, body); + return new Response { ContentType = "application/xml"}; + }; + + Post["/user/createWithArray", true] = async (parameters, ct) => + { + var body = this.Bind>(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUsersWithArrayInput'"); + + await service.CreateUsersWithArrayInput(Context, body); + return new Response { ContentType = "application/xml"}; + }; + + Post["/user/createWithList", true] = async (parameters, ct) => + { + var body = this.Bind>(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUsersWithListInput'"); + + await service.CreateUsersWithListInput(Context, body); + return new Response { ContentType = "application/xml"}; + }; + + Delete["/user/{username}", true] = async (parameters, ct) => + { + var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Path); + Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'DeleteUser'"); + + await service.DeleteUser(Context, username); + return new Response { ContentType = "application/xml"}; + }; + + Get["/user/{username}", true] = async (parameters, ct) => + { + var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Path); + Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'GetUserByName'"); + + return service.GetUserByName(Context, username); + }; + + Get["/user/login", true] = async (parameters, ct) => + { + var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Query); + var password = Parameters.ValueOf(parameters, Context.Request, "password", ParameterType.Query); + Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'LoginUser'"); + + Preconditions.IsNotNull(password, "Required parameter: 'password' is missing at 'LoginUser'"); + + return service.LoginUser(Context, username, password); + }; + + Get["/user/logout", true] = async (parameters, ct) => + { + + await service.LogoutUser(Context); + return new Response { ContentType = "application/xml"}; + }; + + Put["/user/{username}", true] = async (parameters, ct) => + { + var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Path); + var body = this.Bind(); + Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'UpdateUser'"); + + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdateUser'"); + + await service.UpdateUser(Context, username, body); + return new Response { ContentType = "application/xml"}; + }; + } + } + + /// + /// Service handling User requests. + /// + public interface UserService + { + /// + /// This can only be done by the logged in user. + /// + /// Context of request + /// Created user object + /// + Task CreateUser(NancyContext context, User body); + + /// + /// + /// + /// Context of request + /// List of user object + /// + Task CreateUsersWithArrayInput(NancyContext context, List body); + + /// + /// + /// + /// Context of request + /// List of user object + /// + Task CreateUsersWithListInput(NancyContext context, List body); + + /// + /// This can only be done by the logged in user. + /// + /// Context of request + /// The name that needs to be deleted + /// + Task DeleteUser(NancyContext context, string username); + + /// + /// + /// + /// Context of request + /// The name that needs to be fetched. Use user1 for testing. + /// User + Task GetUserByName(NancyContext context, string username); + + /// + /// + /// + /// Context of request + /// The user name for login + /// The password for login in clear text + /// string + Task LoginUser(NancyContext context, string username, string password); + + /// + /// + /// + /// Context of request + /// + Task LogoutUser(NancyContext context); + + /// + /// This can only be done by the logged in user. + /// + /// Context of request + /// name that need to be deleted + /// Updated user object + /// + Task UpdateUser(NancyContext context, string username, User body); + } + + /// + /// Abstraction of UserService. + /// + public abstract class AbstractUserService: UserService + { + public virtual Task CreateUser(NancyContext context, User body) + { + return CreateUser(body); + } + + public virtual Task CreateUsersWithArrayInput(NancyContext context, List body) + { + return CreateUsersWithArrayInput(body); + } + + public virtual Task CreateUsersWithListInput(NancyContext context, List body) + { + return CreateUsersWithListInput(body); + } + + public virtual Task DeleteUser(NancyContext context, string username) + { + return DeleteUser(username); + } + + public virtual Task GetUserByName(NancyContext context, string username) + { + return GetUserByName(username); + } + + public virtual Task LoginUser(NancyContext context, string username, string password) + { + return LoginUser(username, password); + } + + public virtual Task LogoutUser(NancyContext context) + { + return LogoutUser(); + } + + public virtual Task UpdateUser(NancyContext context, string username, User body) + { + return UpdateUser(username, body); + } + + protected abstract Task CreateUser(User body); + + protected abstract Task CreateUsersWithArrayInput(List body); + + protected abstract Task CreateUsersWithListInput(List body); + + protected abstract Task DeleteUser(string username); + + protected abstract Task GetUserByName(string username); + + protected abstract Task LoginUser(string username, string password); + + protected abstract Task LogoutUser(); + + protected abstract Task UpdateUser(string username, User body); + } + +} diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/Parameters.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/Parameters.cs new file mode 100644 index 00000000000..6175758fd9a --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/Parameters.cs @@ -0,0 +1,443 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Nancy; +using NodaTime; +using NodaTime.Text; +using Sharpility.Base; +using Sharpility.Extensions; +using Sharpility.Util; + +namespace IO.Swagger.v2.Utils +{ + internal static class Parameters + { + private static readonly IDictionary> Parsers = CreateParsers(); + + internal static TValue ValueOf(dynamic parameters, Request request, string name, ParameterType parameterType) + { + var valueType = typeof(TValue); + var valueUnderlyingType = Nullable.GetUnderlyingType(valueType); + var isNullable = default(TValue) == null; + string value = RawValueOf(parameters, request, name, parameterType); + Preconditions.Evaluate(!string.IsNullOrEmpty(value) || isNullable, string.Format("Required parameter: '{0}' is missing", name)); + if (value == null && isNullable) + { + return default(TValue); + } + if (valueType.IsEnum || (valueUnderlyingType != null && valueUnderlyingType.IsEnum)) + { + return EnumValueOf(name, value); + } + return ValueOf(parameters, name, value, valueType, request, parameterType); + } + + private static string RawValueOf(dynamic parameters, Request request, string name, ParameterType parameterType) + { + try + { + switch (parameterType) + { + case ParameterType.Query: + string querValue = request.Query[name]; + return querValue; + case ParameterType.Path: + string pathValue = parameters[name]; + return pathValue; + case ParameterType.Header: + var headerValue = request.Headers[name]; + return headerValue != null ? string.Join(",", headerValue) : null; + } + } + catch (Exception e) + { + throw new InvalidOperationException(string.Format("Could not obtain value of '{0}' parameter", name), e); + } + throw new InvalidOperationException(string.Format("Parameter with type: {0} is not supported", parameterType)); + } + + private static TValue EnumValueOf(string name, string value) + { + var valueType = typeof(TValue); + var enumType = valueType.IsEnum ? valueType : Nullable.GetUnderlyingType(valueType); + Preconditions.IsNotNull(enumType, () => new InvalidOperationException( + string.Format("Could not parse parameter: '{0}' to enum. Type {1} is not enum", name, valueType))); + var values = Enum.GetValues(enumType); + foreach (var entry in values) + { + if (entry.ToString().EqualsIgnoreCases(value) + || ((int)entry).ToString().EqualsIgnoreCases(value)) + { + return (TValue)entry; + } + } + throw new ArgumentException(string.Format("Parameter: '{0}' value: '{1}' is not supported. Expected one of: {2}", + name, value, Strings.ToString(values))); + } + + private static TValue ValueOf(dynamic parameters, string name, string value, Type valueType, Request request, ParameterType parameterType) + { + var parser = Parsers.GetIfPresent(valueType); + if (parser != null) + { + return ParseValueUsing(name, value, valueType, parser); + } + if (parameterType == ParameterType.Path) + { + return DynamicValueOf(parameters, name); + } + if (parameterType == ParameterType.Query) + { + return DynamicValueOf(request.Query, name); + } + throw new InvalidOperationException(string.Format("Could not get value for {0} with type {1}", name, valueType)); + } + + private static TValue ParseValueUsing(string name, string value, Type valueType, Func parser) + { + var result = parser(Parameter.Of(name, value)); + try + { + return (TValue)result; + } + catch (InvalidCastException) + { + throw new InvalidOperationException( + string.Format("Could not parse parameter: '{0}' with value: '{1}'. " + + "Received: '{2}', expected: '{3}'.", + name, value, result.GetType(), valueType)); + } + } + + private static TValue DynamicValueOf(dynamic parameters, string name) + { + string value = parameters[name]; + try + { + TValue result = parameters[name]; + return result; + } + catch (InvalidCastException) + { + throw new InvalidOperationException(Strings.Format("Parameter: '{0}' value: '{1}' could not be parsed. " + + "Expected type: '{2}' is not supported", + name, value, typeof(TValue))); + } + catch (Exception e) + { + throw new InvalidOperationException(string.Format("Could not get '{0}' value of '{1}' type dynamicly", + name, typeof(TValue)), e); + } + } + + private static IDictionary> CreateParsers() + { + var parsers = ImmutableDictionary.CreateBuilder>(); + parsers.Put(typeof(string), value => value.Value); + parsers.Put(typeof(bool), SafeParse(bool.Parse)); + parsers.Put(typeof(bool?), SafeParse(bool.Parse)); + parsers.Put(typeof(byte), SafeParse(byte.Parse)); + parsers.Put(typeof(sbyte?), SafeParse(sbyte.Parse)); + parsers.Put(typeof(short), SafeParse(short.Parse)); + parsers.Put(typeof(short?), SafeParse(short.Parse)); + parsers.Put(typeof(ushort), SafeParse(ushort.Parse)); + parsers.Put(typeof(ushort?), SafeParse(ushort.Parse)); + parsers.Put(typeof(int), SafeParse(int.Parse)); + parsers.Put(typeof(int?), SafeParse(int.Parse)); + parsers.Put(typeof(uint), SafeParse(uint.Parse)); + parsers.Put(typeof(uint?), SafeParse(uint.Parse)); + parsers.Put(typeof(long), SafeParse(long.Parse)); + parsers.Put(typeof(long?), SafeParse(long.Parse)); + parsers.Put(typeof(ulong), SafeParse(ulong.Parse)); + parsers.Put(typeof(ulong?), SafeParse(ulong.Parse)); + parsers.Put(typeof(float), SafeParse(float.Parse)); + parsers.Put(typeof(float?), SafeParse(float.Parse)); + parsers.Put(typeof(double), SafeParse(double.Parse)); + parsers.Put(typeof(double?), SafeParse(double.Parse)); + parsers.Put(typeof(decimal), SafeParse(decimal.Parse)); + parsers.Put(typeof(decimal?), SafeParse(decimal.Parse)); + parsers.Put(typeof(DateTime), SafeParse(DateTime.Parse)); + parsers.Put(typeof(DateTime?), SafeParse(DateTime.Parse)); + parsers.Put(typeof(TimeSpan), SafeParse(TimeSpan.Parse)); + parsers.Put(typeof(TimeSpan?), SafeParse(TimeSpan.Parse)); + parsers.Put(typeof(ZonedDateTime), SafeParse(ParseZonedDateTime)); + parsers.Put(typeof(ZonedDateTime?), SafeParse(ParseZonedDateTime)); + parsers.Put(typeof(LocalTime), SafeParse(ParseLocalTime)); + parsers.Put(typeof(LocalTime?), SafeParse(ParseLocalTime)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(value => value)); + parsers.Put(typeof(ICollection), ImmutableListParse(value => value)); + parsers.Put(typeof(IList), ImmutableListParse(value => value)); + parsers.Put(typeof(List), ListParse(value => value)); + parsers.Put(typeof(ISet), ImmutableListParse(value => value)); + parsers.Put(typeof(HashSet), SetParse(value => value)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(bool.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(bool.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(bool.Parse)); + parsers.Put(typeof(List), NullableListParse(bool.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(bool.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(bool.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(byte.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(byte.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(byte.Parse)); + parsers.Put(typeof(List), ListParse(byte.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(byte.Parse)); + parsers.Put(typeof(HashSet), SetParse(byte.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(sbyte.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(sbyte.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(sbyte.Parse)); + parsers.Put(typeof(List), ListParse(sbyte.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(sbyte.Parse)); + parsers.Put(typeof(HashSet), SetParse(sbyte.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(short.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(short.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(short.Parse)); + parsers.Put(typeof(List), ListParse(short.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(short.Parse)); + parsers.Put(typeof(HashSet), SetParse(short.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(ushort.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(ushort.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(ushort.Parse)); + parsers.Put(typeof(List), ListParse(ushort.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(ushort.Parse)); + parsers.Put(typeof(HashSet), SetParse(ushort.Parse)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(int.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(int.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(int.Parse)); + parsers.Put(typeof(List), NullableListParse(int.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(int.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(int.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(uint.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(uint.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(uint.Parse)); + parsers.Put(typeof(List), ListParse(uint.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(uint.Parse)); + parsers.Put(typeof(HashSet), SetParse(uint.Parse)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(long.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(long.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(long.Parse)); + parsers.Put(typeof(List), NullableListParse(long.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(long.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(long.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(ulong.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(ulong.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(ulong.Parse)); + parsers.Put(typeof(List), ListParse(ulong.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(ulong.Parse)); + parsers.Put(typeof(HashSet), SetParse(ulong.Parse)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(float.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(float.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(float.Parse)); + parsers.Put(typeof(List), NullableListParse(float.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(float.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(float.Parse)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(double.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(double.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(double.Parse)); + parsers.Put(typeof(List), NullableListParse(double.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(double.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(double.Parse)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(decimal.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(decimal.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(decimal.Parse)); + parsers.Put(typeof(List), NullableListParse(decimal.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(decimal.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(decimal.Parse)); + + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(DateTime.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(DateTime.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(DateTime.Parse)); + parsers.Put(typeof(List), NullableListParse(DateTime.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(DateTime.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(DateTime.Parse)); + + parsers.Put(typeof(IEnumerable), ImmutableListParse(TimeSpan.Parse)); + parsers.Put(typeof(ICollection), ImmutableListParse(TimeSpan.Parse)); + parsers.Put(typeof(IList), ImmutableListParse(TimeSpan.Parse)); + parsers.Put(typeof(List), ListParse(TimeSpan.Parse)); + parsers.Put(typeof(ISet), ImmutableSetParse(TimeSpan.Parse)); + parsers.Put(typeof(HashSet), SetParse(TimeSpan.Parse)); + + return parsers.ToImmutableDictionary(); + } + + private static Func SafeParse(Func parse) + { + return parameter => + { + try + { + return parse(parameter.Value); + } + catch (OverflowException) + { + throw ParameterOutOfRange(parameter, typeof(T)); + } + catch (FormatException) + { + throw InvalidParameterFormat(parameter, typeof(T)); + } + catch (Exception e) + { + throw new InvalidOperationException(Strings.Format("Unable to parse parameter: '{0}' with value: '{1}' to {2}", + parameter.Name, parameter.Value, typeof(T)), e); + } + }; + } + + private static Func NullableListParse(Func itemParser) where T: struct + { + return ListParse(it => it.ToNullable(itemParser)); + } + + private static Func ListParse(Func itemParser) + { + return parameter => + { + if (string.IsNullOrEmpty(parameter.Value)) + { + return new List(); + } + return ParseCollection(parameter.Value, itemParser).ToList(); + }; + } + + private static Func NullableImmutableListParse(Func itemParser) where T: struct + { + return ImmutableListParse(it => it.ToNullable(itemParser)); + } + + private static Func ImmutableListParse(Func itemParser) + { + return parameter => + { + if (string.IsNullOrEmpty(parameter.Value)) + { + return Lists.EmptyList(); + } + return ParseCollection(parameter.Value, itemParser).ToImmutableList(); + }; + } + + private static Func NullableSetParse(Func itemParser) where T: struct + { + return SetParse(it => it.ToNullable(itemParser)); + } + + private static Func SetParse(Func itemParser) + { + return parameter => + { + if (string.IsNullOrEmpty(parameter.Value)) + { + return new HashSet(); + } + return ParseCollection(parameter.Value, itemParser).ToSet(); + }; + } + + private static Func NullableImmutableSetParse(Func itemParser) where T: struct + { + return ImmutableSetParse(it => it.ToNullable(itemParser)); + } + + private static Func ImmutableSetParse(Func itemParser) + { + return parameter => + { + if (string.IsNullOrEmpty(parameter.Value)) + { + return Sets.EmptySet(); + } + return ParseCollection(parameter.Value, itemParser).ToImmutableHashSet(); + }; + } + + private static ZonedDateTime ParseZonedDateTime(string value) + { + var dateTime = DateTime.Parse(value); + return new ZonedDateTime(Instant.FromDateTimeUtc(dateTime.ToUniversalTime()), DateTimeZone.Utc); + } + + private static LocalTime ParseLocalTime(string value) + { + return LocalTimePattern.ExtendedIsoPattern.Parse(value).Value; + } + + private static ArgumentException ParameterOutOfRange(Parameter parameter, Type type) + { + return new ArgumentException(Strings.Format("Query: '{0}' value: '{1}' is out of range for: '{2}'", + parameter.Name, parameter.Value, type)); + } + + private static ArgumentException InvalidParameterFormat(Parameter parameter, Type type) + { + return new ArgumentException(Strings.Format("Query '{0}' value: '{1}' format is invalid for: '{2}'", + parameter.Name, parameter.Value, type)); + } + + private static IEnumerable ParseCollection(string value, Func itemParser) + { + var results = value.Split(new[] { ',' }, StringSplitOptions.None) + .Where(it => it != null) + .Select(it => it.Trim()) + .Select(itemParser); + return results; + } + + public static T? ToNullable(this string s, Func itemParser) where T : struct + { + T? result = new T?(); + try + { + if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0) + { + result = itemParser(s); + } + } + catch (Exception e) + { + throw new InvalidOperationException(Strings.Format("Unable to parse value: '{0}' to nullable: '{1}'", s, typeof(T).ToString()), e); + } + return result; + } + + private class Parameter + { + internal string Name { get; private set; } + internal string Value { get; private set; } + + private Parameter(string name, string value) + { + Name = name; + Value = value; + } + + internal static Parameter Of(string name, string value) + { + return new Parameter(name, value); + } + } + } + + internal enum ParameterType + { + Undefined, + Query, + Path, + Header + } +} diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/packages.config b/samples/server/petstore/nancyfx-async/src/IO.Swagger/packages.config new file mode 100644 index 00000000000..e3401566e5d --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/packages.config @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/samples/server/petstore/nancyfx/IO.Swagger.sln b/samples/server/petstore/nancyfx/IO.Swagger.sln index b17b1c49583..1e40deb1a14 100644 --- a/samples/server/petstore/nancyfx/IO.Swagger.sln +++ b/samples/server/petstore/nancyfx/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{CA250BF8-2025-4976-8E5A-10668D3F3D22}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{768B8DC6-54EE-4D40-9B20-7857E1D742A4}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -10,10 +10,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{CA250BF8-2025-4976-8E5A-10668D3F3D22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{CA250BF8-2025-4976-8E5A-10668D3F3D22}.Debug|Any CPU.Build.0 = Debug|Any CPU -{CA250BF8-2025-4976-8E5A-10668D3F3D22}.Release|Any CPU.ActiveCfg = Release|Any CPU -{CA250BF8-2025-4976-8E5A-10668D3F3D22}.Release|Any CPU.Build.0 = Release|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Debug|Any CPU.Build.0 = Debug|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Release|Any CPU.ActiveCfg = Release|Any CPU +{768B8DC6-54EE-4D40-9B20-7857E1D742A4}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj index 79c47a207b3..e1577197b6f 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj @@ -3,7 +3,7 @@ Debug AnyCPU - {CA250BF8-2025-4976-8E5A-10668D3F3D22} + {768B8DC6-54EE-4D40-9B20-7857E1D742A4} Library Properties IO.Swagger.v2 From ce6650321301c88877dad2f013f359259433fe97 Mon Sep 17 00:00:00 2001 From: raffael Date: Tue, 24 Oct 2017 13:53:56 +0200 Subject: [PATCH 3/9] Rename async => asyncServer --- .../io/swagger/codegen/languages/NancyFXServerCodegen.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java index 2a3ff4a096b..9089dddd5dc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java @@ -46,7 +46,7 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { private static final String IMMUTABLE_OPTION = "immutable"; private static final String USE_BASE_PATH = "writeModulePath"; private static final String PACKAGE_CONTEXT = "packageContext"; - private static final String ASYNC = "async"; + private static final String ASYNC_SERVER = "asyncServer"; private static final Map> propertyToSwaggerTypeMapping = createPropertyToSwaggerTypeMapping(); @@ -79,7 +79,7 @@ public NancyFXServerCodegen() { addOption(INTERFACE_PREFIX, INTERFACE_PREFIX_DESC, interfacePrefix); addOption(OPTIONAL_PROJECT_GUID,OPTIONAL_PROJECT_GUID_DESC, null); addOption(PACKAGE_CONTEXT, "Optionally overrides the PackageContext which determines the namespace (namespace=packageName.packageContext). If not set, packageContext will default to basePath.", null); - addOption(ASYNC, "Set to true to enable the generation of async routes.", "false"); + addOption(ASYNC_SERVER, "Set to true to enable the generation of async routes/endpoints.", "false"); // CLI Switches addSwitch(SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_BY_REQUIRED_FLAG_DESC, sortParamsByRequiredFlag); From 46383b016b0efa955c79c2f370ace2484c06bfb6 Mon Sep 17 00:00:00 2001 From: raffael Date: Tue, 24 Oct 2017 13:55:46 +0200 Subject: [PATCH 4/9] update bin/nancyfx-petstore-server-async.sh --- bin/nancyfx-petstore-server-async.sh | 2 +- .../src/IO.Swagger/Modules/PetModule.cs | 82 ++++++++--------- .../src/IO.Swagger/Modules/StoreModule.cs | 38 ++++---- .../src/IO.Swagger/Modules/UserModule.cs | 90 +++++++++---------- 4 files changed, 106 insertions(+), 106 deletions(-) diff --git a/bin/nancyfx-petstore-server-async.sh b/bin/nancyfx-petstore-server-async.sh index e5198c4fc1b..b07c010731f 100644 --- a/bin/nancyfx-petstore-server-async.sh +++ b/bin/nancyfx-petstore-server-async.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="generate $@ -t modules/swagger-codegen/src/main/resources/nancyfx -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nancyfx -o samples/server/petstore/nancyfx-async --additional-properties packageGuid={768B8DC6-54EE-4D40-9B20-7857E1D742A4},async=true" +ags="generate $@ -t modules/swagger-codegen/src/main/resources/nancyfx -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nancyfx -o samples/server/petstore/nancyfx-async --additional-properties packageGuid={768B8DC6-54EE-4D40-9B20-7857E1D742A4},asyncServer=true" java $JAVA_OPTS -jar $executable $ags diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs index 27841e5c662..f27290da30b 100644 --- a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs @@ -6,7 +6,7 @@ using IO.Swagger.v2.Models; using IO.Swagger.v2.Utils; using NodaTime; -using System.Threading.Tasks; + namespace IO.Swagger.v2.Modules { @@ -32,26 +32,26 @@ public sealed class PetModule : NancyModule /// Service handling requests public PetModule(PetService service) : base("/v2") { - Post["/pet", true] = async (parameters, ct) => + Post["/pet"] = parameters => { var body = this.Bind(); Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'AddPet'"); - await service.AddPet(Context, body); + service.AddPet(Context, body); return new Response { ContentType = "application/xml"}; }; - Delete["/pet/{petId}", true] = async (parameters, ct) => + Delete["/pet/{petId}"] = parameters => { var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); var apiKey = Parameters.ValueOf(parameters, Context.Request, "apiKey", ParameterType.Header); Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'DeletePet'"); - await service.DeletePet(Context, petId, apiKey); + service.DeletePet(Context, petId, apiKey); return new Response { ContentType = "application/xml"}; }; - Get["/pet/findByStatus", true] = async (parameters, ct) => + Get["/pet/findByStatus"] = parameters => { var status = Parameters.ValueOf(parameters, Context.Request, "status", ParameterType.Query); Preconditions.IsNotNull(status, "Required parameter: 'status' is missing at 'FindPetsByStatus'"); @@ -59,7 +59,7 @@ public PetModule(PetService service) : base("/v2") return service.FindPetsByStatus(Context, status).ToArray(); }; - Get["/pet/findByTags", true] = async (parameters, ct) => + Get["/pet/findByTags"] = parameters => { var tags = Parameters.ValueOf>(parameters, Context.Request, "tags", ParameterType.Query); Preconditions.IsNotNull(tags, "Required parameter: 'tags' is missing at 'FindPetsByTags'"); @@ -67,7 +67,7 @@ public PetModule(PetService service) : base("/v2") return service.FindPetsByTags(Context, tags).ToArray(); }; - Get["/pet/{petId}", true] = async (parameters, ct) => + Get["/pet/{petId}"] = parameters => { var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'GetPetById'"); @@ -75,27 +75,27 @@ public PetModule(PetService service) : base("/v2") return service.GetPetById(Context, petId); }; - Put["/pet", true] = async (parameters, ct) => + Put["/pet"] = parameters => { var body = this.Bind(); Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdatePet'"); - await service.UpdatePet(Context, body); + service.UpdatePet(Context, body); return new Response { ContentType = "application/xml"}; }; - Post["/pet/{petId}", true] = async (parameters, ct) => + Post["/pet/{petId}"] = parameters => { var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); var name = Parameters.ValueOf(parameters, Context.Request, "name", ParameterType.Undefined); var status = Parameters.ValueOf(parameters, Context.Request, "status", ParameterType.Undefined); Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UpdatePetWithForm'"); - await service.UpdatePetWithForm(Context, petId, name, status); + service.UpdatePetWithForm(Context, petId, name, status); return new Response { ContentType = "application/xml"}; }; - Post["/pet/{petId}/uploadImage", true] = async (parameters, ct) => + Post["/pet/{petId}/uploadImage"] = parameters => { var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); var additionalMetadata = Parameters.ValueOf(parameters, Context.Request, "additionalMetadata", ParameterType.Undefined); @@ -118,7 +118,7 @@ public interface PetService /// Context of request /// Pet object that needs to be added to the store /// - Task AddPet(NancyContext context, Pet body); + void AddPet(NancyContext context, Pet body); /// /// @@ -127,7 +127,7 @@ public interface PetService /// Pet id to delete /// (optional) /// - Task DeletePet(NancyContext context, long? petId, string apiKey); + void DeletePet(NancyContext context, long? petId, string apiKey); /// /// Multiple status values can be provided with comma separated strings @@ -135,7 +135,7 @@ public interface PetService /// Context of request /// Status values that need to be considered for filter /// List<Pet> - Task> FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status); + List FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status); /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -143,7 +143,7 @@ public interface PetService /// Context of request /// Tags to filter by /// List<Pet> - Task> FindPetsByTags(NancyContext context, List tags); + List FindPetsByTags(NancyContext context, List tags); /// /// Returns a single pet @@ -151,7 +151,7 @@ public interface PetService /// Context of request /// ID of pet to return /// Pet - Task GetPetById(NancyContext context, long? petId); + Pet GetPetById(NancyContext context, long? petId); /// /// @@ -159,7 +159,7 @@ public interface PetService /// Context of request /// Pet object that needs to be added to the store /// - Task UpdatePet(NancyContext context, Pet body); + void UpdatePet(NancyContext context, Pet body); /// /// @@ -169,7 +169,7 @@ public interface PetService /// Updated name of the pet (optional) /// Updated status of the pet (optional) /// - Task UpdatePetWithForm(NancyContext context, long? petId, string name, string status); + void UpdatePetWithForm(NancyContext context, long? petId, string name, string status); /// /// @@ -179,7 +179,7 @@ public interface PetService /// Additional data to pass to server (optional) /// file to upload (optional) /// ApiResponse - Task UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file); + ApiResponse UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file); } /// @@ -187,61 +187,61 @@ public interface PetService /// public abstract class AbstractPetService: PetService { - public virtual Task AddPet(NancyContext context, Pet body) + public virtual void AddPet(NancyContext context, Pet body) { - return AddPet(body); + AddPet(body); } - public virtual Task DeletePet(NancyContext context, long? petId, string apiKey) + public virtual void DeletePet(NancyContext context, long? petId, string apiKey) { - return DeletePet(petId, apiKey); + DeletePet(petId, apiKey); } - public virtual Task> FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status) + public virtual List FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status) { return FindPetsByStatus(status); } - public virtual Task> FindPetsByTags(NancyContext context, List tags) + public virtual List FindPetsByTags(NancyContext context, List tags) { return FindPetsByTags(tags); } - public virtual Task GetPetById(NancyContext context, long? petId) + public virtual Pet GetPetById(NancyContext context, long? petId) { return GetPetById(petId); } - public virtual Task UpdatePet(NancyContext context, Pet body) + public virtual void UpdatePet(NancyContext context, Pet body) { - return UpdatePet(body); + UpdatePet(body); } - public virtual Task UpdatePetWithForm(NancyContext context, long? petId, string name, string status) + public virtual void UpdatePetWithForm(NancyContext context, long? petId, string name, string status) { - return UpdatePetWithForm(petId, name, status); + UpdatePetWithForm(petId, name, status); } - public virtual Task UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file) + public virtual ApiResponse UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file) { return UploadFile(petId, additionalMetadata, file); } - protected abstract Task AddPet(Pet body); + protected abstract void AddPet(Pet body); - protected abstract Task DeletePet(long? petId, string apiKey); + protected abstract void DeletePet(long? petId, string apiKey); - protected abstract Task> FindPetsByStatus(FindPetsByStatusStatusEnum? status); + protected abstract List FindPetsByStatus(FindPetsByStatusStatusEnum? status); - protected abstract Task> FindPetsByTags(List tags); + protected abstract List FindPetsByTags(List tags); - protected abstract Task GetPetById(long? petId); + protected abstract Pet GetPetById(long? petId); - protected abstract Task UpdatePet(Pet body); + protected abstract void UpdatePet(Pet body); - protected abstract Task UpdatePetWithForm(long? petId, string name, string status); + protected abstract void UpdatePetWithForm(long? petId, string name, string status); - protected abstract Task UploadFile(long? petId, string additionalMetadata, System.IO.Stream file); + protected abstract ApiResponse UploadFile(long? petId, string additionalMetadata, System.IO.Stream file); } } diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs index b494e8a4e74..17525f5c6bb 100644 --- a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs @@ -6,7 +6,7 @@ using IO.Swagger.v2.Models; using IO.Swagger.v2.Utils; using NodaTime; -using System.Threading.Tasks; + namespace IO.Swagger.v2.Modules { @@ -22,22 +22,22 @@ public sealed class StoreModule : NancyModule /// Service handling requests public StoreModule(StoreService service) : base("/v2") { - Delete["/store/order/{orderId}", true] = async (parameters, ct) => + Delete["/store/order/{orderId}"] = parameters => { var orderId = Parameters.ValueOf(parameters, Context.Request, "orderId", ParameterType.Path); Preconditions.IsNotNull(orderId, "Required parameter: 'orderId' is missing at 'DeleteOrder'"); - await service.DeleteOrder(Context, orderId); + service.DeleteOrder(Context, orderId); return new Response { ContentType = "application/xml"}; }; - Get["/store/inventory", true] = async (parameters, ct) => + Get["/store/inventory"] = parameters => { return service.GetInventory(Context); }; - Get["/store/order/{orderId}", true] = async (parameters, ct) => + Get["/store/order/{orderId}"] = parameters => { var orderId = Parameters.ValueOf(parameters, Context.Request, "orderId", ParameterType.Path); Preconditions.IsNotNull(orderId, "Required parameter: 'orderId' is missing at 'GetOrderById'"); @@ -45,7 +45,7 @@ public StoreModule(StoreService service) : base("/v2") return service.GetOrderById(Context, orderId); }; - Post["/store/order", true] = async (parameters, ct) => + Post["/store/order"] = parameters => { var body = this.Bind(); Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'PlaceOrder'"); @@ -66,14 +66,14 @@ public interface StoreService /// Context of request /// ID of the order that needs to be deleted /// - Task DeleteOrder(NancyContext context, string orderId); + void DeleteOrder(NancyContext context, string orderId); /// /// Returns a map of status codes to quantities /// /// Context of request /// Dictionary<string, int?> - Task> GetInventory(NancyContext context); + Dictionary GetInventory(NancyContext context); /// /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions @@ -81,7 +81,7 @@ public interface StoreService /// Context of request /// ID of pet that needs to be fetched /// Order - Task GetOrderById(NancyContext context, long? orderId); + Order GetOrderById(NancyContext context, long? orderId); /// /// @@ -89,7 +89,7 @@ public interface StoreService /// Context of request /// order placed for purchasing the pet /// Order - Task PlaceOrder(NancyContext context, Order body); + Order PlaceOrder(NancyContext context, Order body); } /// @@ -97,33 +97,33 @@ public interface StoreService /// public abstract class AbstractStoreService: StoreService { - public virtual Task DeleteOrder(NancyContext context, string orderId) + public virtual void DeleteOrder(NancyContext context, string orderId) { - return DeleteOrder(orderId); + DeleteOrder(orderId); } - public virtual Task> GetInventory(NancyContext context) + public virtual Dictionary GetInventory(NancyContext context) { return GetInventory(); } - public virtual Task GetOrderById(NancyContext context, long? orderId) + public virtual Order GetOrderById(NancyContext context, long? orderId) { return GetOrderById(orderId); } - public virtual Task PlaceOrder(NancyContext context, Order body) + public virtual Order PlaceOrder(NancyContext context, Order body) { return PlaceOrder(body); } - protected abstract Task DeleteOrder(string orderId); + protected abstract void DeleteOrder(string orderId); - protected abstract Task> GetInventory(); + protected abstract Dictionary GetInventory(); - protected abstract Task GetOrderById(long? orderId); + protected abstract Order GetOrderById(long? orderId); - protected abstract Task PlaceOrder(Order body); + protected abstract Order PlaceOrder(Order body); } } diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs index bba288d82e7..3abe9a8fc14 100644 --- a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs @@ -6,7 +6,7 @@ using IO.Swagger.v2.Models; using IO.Swagger.v2.Utils; using NodaTime; -using System.Threading.Tasks; + namespace IO.Swagger.v2.Modules { @@ -22,43 +22,43 @@ public sealed class UserModule : NancyModule /// Service handling requests public UserModule(UserService service) : base("/v2") { - Post["/user", true] = async (parameters, ct) => + Post["/user"] = parameters => { var body = this.Bind(); Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUser'"); - await service.CreateUser(Context, body); + service.CreateUser(Context, body); return new Response { ContentType = "application/xml"}; }; - Post["/user/createWithArray", true] = async (parameters, ct) => + Post["/user/createWithArray"] = parameters => { var body = this.Bind>(); Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUsersWithArrayInput'"); - await service.CreateUsersWithArrayInput(Context, body); + service.CreateUsersWithArrayInput(Context, body); return new Response { ContentType = "application/xml"}; }; - Post["/user/createWithList", true] = async (parameters, ct) => + Post["/user/createWithList"] = parameters => { var body = this.Bind>(); Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUsersWithListInput'"); - await service.CreateUsersWithListInput(Context, body); + service.CreateUsersWithListInput(Context, body); return new Response { ContentType = "application/xml"}; }; - Delete["/user/{username}", true] = async (parameters, ct) => + Delete["/user/{username}"] = parameters => { var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Path); Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'DeleteUser'"); - await service.DeleteUser(Context, username); + service.DeleteUser(Context, username); return new Response { ContentType = "application/xml"}; }; - Get["/user/{username}", true] = async (parameters, ct) => + Get["/user/{username}"] = parameters => { var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Path); Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'GetUserByName'"); @@ -66,7 +66,7 @@ public UserModule(UserService service) : base("/v2") return service.GetUserByName(Context, username); }; - Get["/user/login", true] = async (parameters, ct) => + Get["/user/login"] = parameters => { var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Query); var password = Parameters.ValueOf(parameters, Context.Request, "password", ParameterType.Query); @@ -77,14 +77,14 @@ public UserModule(UserService service) : base("/v2") return service.LoginUser(Context, username, password); }; - Get["/user/logout", true] = async (parameters, ct) => + Get["/user/logout"] = parameters => { - await service.LogoutUser(Context); + service.LogoutUser(Context); return new Response { ContentType = "application/xml"}; }; - Put["/user/{username}", true] = async (parameters, ct) => + Put["/user/{username}"] = parameters => { var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Path); var body = this.Bind(); @@ -92,7 +92,7 @@ public UserModule(UserService service) : base("/v2") Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdateUser'"); - await service.UpdateUser(Context, username, body); + service.UpdateUser(Context, username, body); return new Response { ContentType = "application/xml"}; }; } @@ -109,7 +109,7 @@ public interface UserService /// Context of request /// Created user object /// - Task CreateUser(NancyContext context, User body); + void CreateUser(NancyContext context, User body); /// /// @@ -117,7 +117,7 @@ public interface UserService /// Context of request /// List of user object /// - Task CreateUsersWithArrayInput(NancyContext context, List body); + void CreateUsersWithArrayInput(NancyContext context, List body); /// /// @@ -125,7 +125,7 @@ public interface UserService /// Context of request /// List of user object /// - Task CreateUsersWithListInput(NancyContext context, List body); + void CreateUsersWithListInput(NancyContext context, List body); /// /// This can only be done by the logged in user. @@ -133,7 +133,7 @@ public interface UserService /// Context of request /// The name that needs to be deleted /// - Task DeleteUser(NancyContext context, string username); + void DeleteUser(NancyContext context, string username); /// /// @@ -141,7 +141,7 @@ public interface UserService /// Context of request /// The name that needs to be fetched. Use user1 for testing. /// User - Task GetUserByName(NancyContext context, string username); + User GetUserByName(NancyContext context, string username); /// /// @@ -150,14 +150,14 @@ public interface UserService /// The user name for login /// The password for login in clear text /// string - Task LoginUser(NancyContext context, string username, string password); + string LoginUser(NancyContext context, string username, string password); /// /// /// /// Context of request /// - Task LogoutUser(NancyContext context); + void LogoutUser(NancyContext context); /// /// This can only be done by the logged in user. @@ -166,7 +166,7 @@ public interface UserService /// name that need to be deleted /// Updated user object /// - Task UpdateUser(NancyContext context, string username, User body); + void UpdateUser(NancyContext context, string username, User body); } /// @@ -174,61 +174,61 @@ public interface UserService /// public abstract class AbstractUserService: UserService { - public virtual Task CreateUser(NancyContext context, User body) + public virtual void CreateUser(NancyContext context, User body) { - return CreateUser(body); + CreateUser(body); } - public virtual Task CreateUsersWithArrayInput(NancyContext context, List body) + public virtual void CreateUsersWithArrayInput(NancyContext context, List body) { - return CreateUsersWithArrayInput(body); + CreateUsersWithArrayInput(body); } - public virtual Task CreateUsersWithListInput(NancyContext context, List body) + public virtual void CreateUsersWithListInput(NancyContext context, List body) { - return CreateUsersWithListInput(body); + CreateUsersWithListInput(body); } - public virtual Task DeleteUser(NancyContext context, string username) + public virtual void DeleteUser(NancyContext context, string username) { - return DeleteUser(username); + DeleteUser(username); } - public virtual Task GetUserByName(NancyContext context, string username) + public virtual User GetUserByName(NancyContext context, string username) { return GetUserByName(username); } - public virtual Task LoginUser(NancyContext context, string username, string password) + public virtual string LoginUser(NancyContext context, string username, string password) { return LoginUser(username, password); } - public virtual Task LogoutUser(NancyContext context) + public virtual void LogoutUser(NancyContext context) { - return LogoutUser(); + LogoutUser(); } - public virtual Task UpdateUser(NancyContext context, string username, User body) + public virtual void UpdateUser(NancyContext context, string username, User body) { - return UpdateUser(username, body); + UpdateUser(username, body); } - protected abstract Task CreateUser(User body); + protected abstract void CreateUser(User body); - protected abstract Task CreateUsersWithArrayInput(List body); + protected abstract void CreateUsersWithArrayInput(List body); - protected abstract Task CreateUsersWithListInput(List body); + protected abstract void CreateUsersWithListInput(List body); - protected abstract Task DeleteUser(string username); + protected abstract void DeleteUser(string username); - protected abstract Task GetUserByName(string username); + protected abstract User GetUserByName(string username); - protected abstract Task LoginUser(string username, string password); + protected abstract string LoginUser(string username, string password); - protected abstract Task LogoutUser(); + protected abstract void LogoutUser(); - protected abstract Task UpdateUser(string username, User body); + protected abstract void UpdateUser(string username, User body); } } From f6e40ea097b5a550f6a34f397806719c13f31256 Mon Sep 17 00:00:00 2001 From: raffael Date: Tue, 24 Oct 2017 15:59:14 +0200 Subject: [PATCH 5/9] rename async => asyncServer in api.mustache + small bugfix --- .../codegen/languages/NancyFXServerCodegen.java | 15 +++++++++++++-- .../src/main/resources/nancyfx/api.mustache | 14 +++++++------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java index 9089dddd5dc..49401cb075a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java @@ -58,6 +58,9 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { private final Multimap childrenByParent = ArrayListMultimap.create(); private final BiMap modelNameMapping = HashBiMap.create(); + /** If set to true, we will generate c# async endpoints and service interfaces */ + private boolean asyncServer = false; + public NancyFXServerCodegen() { outputFolder = "generated-code" + File.separator + getName(); apiTemplateFiles.put("api.mustache", ".cs"); @@ -79,7 +82,6 @@ public NancyFXServerCodegen() { addOption(INTERFACE_PREFIX, INTERFACE_PREFIX_DESC, interfacePrefix); addOption(OPTIONAL_PROJECT_GUID,OPTIONAL_PROJECT_GUID_DESC, null); addOption(PACKAGE_CONTEXT, "Optionally overrides the PackageContext which determines the namespace (namespace=packageName.packageContext). If not set, packageContext will default to basePath.", null); - addOption(ASYNC_SERVER, "Set to true to enable the generation of async routes/endpoints.", "false"); // CLI Switches addSwitch(SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_BY_REQUIRED_FLAG_DESC, sortParamsByRequiredFlag); @@ -89,6 +91,7 @@ public NancyFXServerCodegen() { addSwitch(RETURN_ICOLLECTION, RETURN_ICOLLECTION_DESC, returnICollection); addSwitch(IMMUTABLE_OPTION, "Enabled by default. If disabled generates model classes with setters", true); addSwitch(USE_BASE_PATH, "Enabled by default. If disabled, module paths will not mirror api base path", true); + addSwitch(ASYNC_SERVER, "Set to true to enable the generation of async routes/endpoints.", false); typeMapping.putAll(nodaTimeTypesMappings()); languageSpecificPrimitives.addAll(nodaTimePrimitiveTypes()); @@ -130,6 +133,10 @@ public void processOpts() { setPackageGuid((String) additionalProperties.get(OPTIONAL_PROJECT_GUID)); } + if(additionalProperties.containsKey(ASYNC_SERVER)) { + setAsyncServer(Boolean.parseBoolean((String)additionalProperties.get(ASYNC_SERVER))); + } + additionalProperties.put("packageGuid", packageGuid); setupModelTemplate(); @@ -201,7 +208,11 @@ private String sourceFile(final String fileName) { public void setPackageGuid(String packageGuid) { this.packageGuid = packageGuid; } - + + public void setAsyncServer(boolean asyncServer) { + this.asyncServer = asyncServer; + } + @Override public String apiFileFolder() { return outputFolder + File.separator + sourceFolder() + File.separator + API_NAMESPACE; diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache index 0a9ef48f91c..fec7f9ac3b8 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache @@ -6,7 +6,7 @@ using Sharpility.Base; using {{packageName}}.{{packageContext}}.Models; using {{packageName}}.{{packageContext}}.Utils; using NodaTime; -{{#async}}using System.Threading.Tasks;{{/async}} +{{#asyncServer}}using System.Threading.Tasks;{{/asyncServer}} {{#imports}}using {{import}}; {{/imports}} @@ -25,13 +25,13 @@ namespace {{packageName}}.{{packageContext}}.Modules /// Service handling requests public {{classname}}Module({{interfacePrefix}}{{classname}}Service service) : base("{{{baseContext}}}") { {{#operation}} - {{httpMethod}}["{{{path}}}"{{#async}}, true{{/async}}] = {{#async}}async (parameters, ct){{/async}}{{^async}}parameters{{/async}} => + {{httpMethod}}["{{{path}}}"{{#asyncServer}}, true{{/asyncServer}}] = {{#asyncServer}}async (parameters, ct){{/asyncServer}}{{^asyncServer}}parameters{{/asyncServer}} => { {{#allParams}}{{#isBodyParam}}var {{paramName}} = this.Bind<{{&dataType}}>();{{/isBodyParam}}{{^isBodyParam}}{{#isEnum}}var {{paramName}} = Parameters.ValueOf<{{>innerApiEnumName}}?>({{>innerParameterValueOfArgs}});{{/isEnum}}{{^isEnum}}var {{paramName}} = Parameters.ValueOf<{{&dataType}}>({{>innerParameterValueOfArgs}});{{/isEnum}}{{#hasMore}} {{/hasMore}}{{/isBodyParam}}{{/allParams}}{{#allParams}}{{#required}} Preconditions.IsNotNull({{paramName}}, "Required parameter: '{{paramName}}' is missing at '{{operationId}}'"); {{/required}}{{/allParams}} - {{#returnType}}return {{/returnType}}{{^returnType}}{{#async}}await {{/async}}{{/returnType}}service.{{operationId}}(Context{{#allParams.0}}, {{/allParams.0}}{{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}{{#isListContainer}}.ToArray(){{/isListContainer}}{{/returnType}};{{^returnType}} + {{#returnType}}return {{/returnType}}{{#asyncServer}}await {{/asyncServer}}service.{{operationId}}(Context{{#allParams.0}}, {{/allParams.0}}{{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}{{#isListContainer}}.ToArray(){{/isListContainer}}{{/returnType}};{{^returnType}} return new Response { ContentType = "{{produces.0.mediaType}}"};{{/returnType}} }; {{/operation}} @@ -49,7 +49,7 @@ namespace {{packageName}}.{{packageContext}}.Modules /// Context of request {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} - {{#async}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/async}}{{^async}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/async}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}});{{#hasMore}} + {{#asyncServer}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/asyncServer}}{{^asyncServer}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/asyncServer}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}});{{#hasMore}} {{/hasMore}}{{/operation}} } @@ -59,14 +59,14 @@ namespace {{packageName}}.{{packageContext}}.Modules /// public abstract class Abstract{{classname}}Service: {{interfacePrefix}}{{classname}}Service { - {{#operation}}public virtual {{#async}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/async}}{{^async}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/async}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}}) + {{#operation}}public virtual {{#asyncServer}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/asyncServer}}{{^asyncServer}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/asyncServer}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}}) { - {{^async}}{{#returnType}}return {{/returnType}}{{/async}}{{#async}}return {{/async}}{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{^asyncServer}}{{#returnType}}return {{/returnType}}{{/asyncServer}}{{#asyncServer}}return {{/asyncServer}}{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); }{{#hasMore}} {{/hasMore}}{{/operation}} - {{#operation}}protected abstract {{#async}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/async}}{{^async}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/async}} {{operationId}}({{>paramsList}});{{#hasMore}} + {{#operation}}protected abstract {{#asyncServer}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/asyncServer}}{{^asyncServer}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/asyncServer}} {{operationId}}({{>paramsList}});{{#hasMore}} {{/hasMore}}{{/operation}} } From 134eaca37e08e8d3e2e10992d8387fd2f7ad25f8 Mon Sep 17 00:00:00 2001 From: raffael Date: Tue, 24 Oct 2017 16:05:48 +0200 Subject: [PATCH 6/9] run ./bin/nancyfx-petstore-server.sh and ./bin/nancyfx-petstore-server-async.sh --- .../src/IO.Swagger/Modules/PetModule.cs | 90 +++++++++--------- .../src/IO.Swagger/Modules/StoreModule.cs | 44 ++++----- .../src/IO.Swagger/Modules/UserModule.cs | 94 +++++++++---------- 3 files changed, 114 insertions(+), 114 deletions(-) diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs index f27290da30b..0d4cf8616c7 100644 --- a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs @@ -6,7 +6,7 @@ using IO.Swagger.v2.Models; using IO.Swagger.v2.Utils; using NodaTime; - +using System.Threading.Tasks; namespace IO.Swagger.v2.Modules { @@ -32,77 +32,77 @@ public sealed class PetModule : NancyModule /// Service handling requests public PetModule(PetService service) : base("/v2") { - Post["/pet"] = parameters => + Post["/pet", true] = async (parameters, ct) => { var body = this.Bind(); Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'AddPet'"); - service.AddPet(Context, body); + await service.AddPet(Context, body); return new Response { ContentType = "application/xml"}; }; - Delete["/pet/{petId}"] = parameters => + Delete["/pet/{petId}", true] = async (parameters, ct) => { var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); var apiKey = Parameters.ValueOf(parameters, Context.Request, "apiKey", ParameterType.Header); Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'DeletePet'"); - service.DeletePet(Context, petId, apiKey); + await service.DeletePet(Context, petId, apiKey); return new Response { ContentType = "application/xml"}; }; - Get["/pet/findByStatus"] = parameters => + Get["/pet/findByStatus", true] = async (parameters, ct) => { var status = Parameters.ValueOf(parameters, Context.Request, "status", ParameterType.Query); Preconditions.IsNotNull(status, "Required parameter: 'status' is missing at 'FindPetsByStatus'"); - return service.FindPetsByStatus(Context, status).ToArray(); + return await service.FindPetsByStatus(Context, status).ToArray(); }; - Get["/pet/findByTags"] = parameters => + Get["/pet/findByTags", true] = async (parameters, ct) => { var tags = Parameters.ValueOf>(parameters, Context.Request, "tags", ParameterType.Query); Preconditions.IsNotNull(tags, "Required parameter: 'tags' is missing at 'FindPetsByTags'"); - return service.FindPetsByTags(Context, tags).ToArray(); + return await service.FindPetsByTags(Context, tags).ToArray(); }; - Get["/pet/{petId}"] = parameters => + Get["/pet/{petId}", true] = async (parameters, ct) => { var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'GetPetById'"); - return service.GetPetById(Context, petId); + return await service.GetPetById(Context, petId); }; - Put["/pet"] = parameters => + Put["/pet", true] = async (parameters, ct) => { var body = this.Bind(); Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdatePet'"); - service.UpdatePet(Context, body); + await service.UpdatePet(Context, body); return new Response { ContentType = "application/xml"}; }; - Post["/pet/{petId}"] = parameters => + Post["/pet/{petId}", true] = async (parameters, ct) => { var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); var name = Parameters.ValueOf(parameters, Context.Request, "name", ParameterType.Undefined); var status = Parameters.ValueOf(parameters, Context.Request, "status", ParameterType.Undefined); Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UpdatePetWithForm'"); - service.UpdatePetWithForm(Context, petId, name, status); + await service.UpdatePetWithForm(Context, petId, name, status); return new Response { ContentType = "application/xml"}; }; - Post["/pet/{petId}/uploadImage"] = parameters => + Post["/pet/{petId}/uploadImage", true] = async (parameters, ct) => { var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); var additionalMetadata = Parameters.ValueOf(parameters, Context.Request, "additionalMetadata", ParameterType.Undefined); var file = Parameters.ValueOf(parameters, Context.Request, "file", ParameterType.Undefined); Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UploadFile'"); - return service.UploadFile(Context, petId, additionalMetadata, file); + return await service.UploadFile(Context, petId, additionalMetadata, file); }; } } @@ -118,7 +118,7 @@ public interface PetService /// Context of request /// Pet object that needs to be added to the store /// - void AddPet(NancyContext context, Pet body); + Task AddPet(NancyContext context, Pet body); /// /// @@ -127,7 +127,7 @@ public interface PetService /// Pet id to delete /// (optional) /// - void DeletePet(NancyContext context, long? petId, string apiKey); + Task DeletePet(NancyContext context, long? petId, string apiKey); /// /// Multiple status values can be provided with comma separated strings @@ -135,7 +135,7 @@ public interface PetService /// Context of request /// Status values that need to be considered for filter /// List<Pet> - List FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status); + Task> FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status); /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -143,7 +143,7 @@ public interface PetService /// Context of request /// Tags to filter by /// List<Pet> - List FindPetsByTags(NancyContext context, List tags); + Task> FindPetsByTags(NancyContext context, List tags); /// /// Returns a single pet @@ -151,7 +151,7 @@ public interface PetService /// Context of request /// ID of pet to return /// Pet - Pet GetPetById(NancyContext context, long? petId); + Task GetPetById(NancyContext context, long? petId); /// /// @@ -159,7 +159,7 @@ public interface PetService /// Context of request /// Pet object that needs to be added to the store /// - void UpdatePet(NancyContext context, Pet body); + Task UpdatePet(NancyContext context, Pet body); /// /// @@ -169,7 +169,7 @@ public interface PetService /// Updated name of the pet (optional) /// Updated status of the pet (optional) /// - void UpdatePetWithForm(NancyContext context, long? petId, string name, string status); + Task UpdatePetWithForm(NancyContext context, long? petId, string name, string status); /// /// @@ -179,7 +179,7 @@ public interface PetService /// Additional data to pass to server (optional) /// file to upload (optional) /// ApiResponse - ApiResponse UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file); + Task UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file); } /// @@ -187,61 +187,61 @@ public interface PetService /// public abstract class AbstractPetService: PetService { - public virtual void AddPet(NancyContext context, Pet body) + public virtual Task AddPet(NancyContext context, Pet body) { - AddPet(body); + return AddPet(body); } - public virtual void DeletePet(NancyContext context, long? petId, string apiKey) + public virtual Task DeletePet(NancyContext context, long? petId, string apiKey) { - DeletePet(petId, apiKey); + return DeletePet(petId, apiKey); } - public virtual List FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status) + public virtual Task> FindPetsByStatus(NancyContext context, FindPetsByStatusStatusEnum? status) { return FindPetsByStatus(status); } - public virtual List FindPetsByTags(NancyContext context, List tags) + public virtual Task> FindPetsByTags(NancyContext context, List tags) { return FindPetsByTags(tags); } - public virtual Pet GetPetById(NancyContext context, long? petId) + public virtual Task GetPetById(NancyContext context, long? petId) { return GetPetById(petId); } - public virtual void UpdatePet(NancyContext context, Pet body) + public virtual Task UpdatePet(NancyContext context, Pet body) { - UpdatePet(body); + return UpdatePet(body); } - public virtual void UpdatePetWithForm(NancyContext context, long? petId, string name, string status) + public virtual Task UpdatePetWithForm(NancyContext context, long? petId, string name, string status) { - UpdatePetWithForm(petId, name, status); + return UpdatePetWithForm(petId, name, status); } - public virtual ApiResponse UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file) + public virtual Task UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file) { return UploadFile(petId, additionalMetadata, file); } - protected abstract void AddPet(Pet body); + protected abstract Task AddPet(Pet body); - protected abstract void DeletePet(long? petId, string apiKey); + protected abstract Task DeletePet(long? petId, string apiKey); - protected abstract List FindPetsByStatus(FindPetsByStatusStatusEnum? status); + protected abstract Task> FindPetsByStatus(FindPetsByStatusStatusEnum? status); - protected abstract List FindPetsByTags(List tags); + protected abstract Task> FindPetsByTags(List tags); - protected abstract Pet GetPetById(long? petId); + protected abstract Task GetPetById(long? petId); - protected abstract void UpdatePet(Pet body); + protected abstract Task UpdatePet(Pet body); - protected abstract void UpdatePetWithForm(long? petId, string name, string status); + protected abstract Task UpdatePetWithForm(long? petId, string name, string status); - protected abstract ApiResponse UploadFile(long? petId, string additionalMetadata, System.IO.Stream file); + protected abstract Task UploadFile(long? petId, string additionalMetadata, System.IO.Stream file); } } diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs index 17525f5c6bb..30c46234256 100644 --- a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/StoreModule.cs @@ -6,7 +6,7 @@ using IO.Swagger.v2.Models; using IO.Swagger.v2.Utils; using NodaTime; - +using System.Threading.Tasks; namespace IO.Swagger.v2.Modules { @@ -22,35 +22,35 @@ public sealed class StoreModule : NancyModule /// Service handling requests public StoreModule(StoreService service) : base("/v2") { - Delete["/store/order/{orderId}"] = parameters => + Delete["/store/order/{orderId}", true] = async (parameters, ct) => { var orderId = Parameters.ValueOf(parameters, Context.Request, "orderId", ParameterType.Path); Preconditions.IsNotNull(orderId, "Required parameter: 'orderId' is missing at 'DeleteOrder'"); - service.DeleteOrder(Context, orderId); + await service.DeleteOrder(Context, orderId); return new Response { ContentType = "application/xml"}; }; - Get["/store/inventory"] = parameters => + Get["/store/inventory", true] = async (parameters, ct) => { - return service.GetInventory(Context); + return await service.GetInventory(Context); }; - Get["/store/order/{orderId}"] = parameters => + Get["/store/order/{orderId}", true] = async (parameters, ct) => { var orderId = Parameters.ValueOf(parameters, Context.Request, "orderId", ParameterType.Path); Preconditions.IsNotNull(orderId, "Required parameter: 'orderId' is missing at 'GetOrderById'"); - return service.GetOrderById(Context, orderId); + return await service.GetOrderById(Context, orderId); }; - Post["/store/order"] = parameters => + Post["/store/order", true] = async (parameters, ct) => { var body = this.Bind(); Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'PlaceOrder'"); - return service.PlaceOrder(Context, body); + return await service.PlaceOrder(Context, body); }; } } @@ -66,14 +66,14 @@ public interface StoreService /// Context of request /// ID of the order that needs to be deleted /// - void DeleteOrder(NancyContext context, string orderId); + Task DeleteOrder(NancyContext context, string orderId); /// /// Returns a map of status codes to quantities /// /// Context of request /// Dictionary<string, int?> - Dictionary GetInventory(NancyContext context); + Task> GetInventory(NancyContext context); /// /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions @@ -81,7 +81,7 @@ public interface StoreService /// Context of request /// ID of pet that needs to be fetched /// Order - Order GetOrderById(NancyContext context, long? orderId); + Task GetOrderById(NancyContext context, long? orderId); /// /// @@ -89,7 +89,7 @@ public interface StoreService /// Context of request /// order placed for purchasing the pet /// Order - Order PlaceOrder(NancyContext context, Order body); + Task PlaceOrder(NancyContext context, Order body); } /// @@ -97,33 +97,33 @@ public interface StoreService /// public abstract class AbstractStoreService: StoreService { - public virtual void DeleteOrder(NancyContext context, string orderId) + public virtual Task DeleteOrder(NancyContext context, string orderId) { - DeleteOrder(orderId); + return DeleteOrder(orderId); } - public virtual Dictionary GetInventory(NancyContext context) + public virtual Task> GetInventory(NancyContext context) { return GetInventory(); } - public virtual Order GetOrderById(NancyContext context, long? orderId) + public virtual Task GetOrderById(NancyContext context, long? orderId) { return GetOrderById(orderId); } - public virtual Order PlaceOrder(NancyContext context, Order body) + public virtual Task PlaceOrder(NancyContext context, Order body) { return PlaceOrder(body); } - protected abstract void DeleteOrder(string orderId); + protected abstract Task DeleteOrder(string orderId); - protected abstract Dictionary GetInventory(); + protected abstract Task> GetInventory(); - protected abstract Order GetOrderById(long? orderId); + protected abstract Task GetOrderById(long? orderId); - protected abstract Order PlaceOrder(Order body); + protected abstract Task PlaceOrder(Order body); } } diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs index 3abe9a8fc14..4faf9e38dbd 100644 --- a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/UserModule.cs @@ -6,7 +6,7 @@ using IO.Swagger.v2.Models; using IO.Swagger.v2.Utils; using NodaTime; - +using System.Threading.Tasks; namespace IO.Swagger.v2.Modules { @@ -22,51 +22,51 @@ public sealed class UserModule : NancyModule /// Service handling requests public UserModule(UserService service) : base("/v2") { - Post["/user"] = parameters => + Post["/user", true] = async (parameters, ct) => { var body = this.Bind(); Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUser'"); - service.CreateUser(Context, body); + await service.CreateUser(Context, body); return new Response { ContentType = "application/xml"}; }; - Post["/user/createWithArray"] = parameters => + Post["/user/createWithArray", true] = async (parameters, ct) => { var body = this.Bind>(); Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUsersWithArrayInput'"); - service.CreateUsersWithArrayInput(Context, body); + await service.CreateUsersWithArrayInput(Context, body); return new Response { ContentType = "application/xml"}; }; - Post["/user/createWithList"] = parameters => + Post["/user/createWithList", true] = async (parameters, ct) => { var body = this.Bind>(); Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUsersWithListInput'"); - service.CreateUsersWithListInput(Context, body); + await service.CreateUsersWithListInput(Context, body); return new Response { ContentType = "application/xml"}; }; - Delete["/user/{username}"] = parameters => + Delete["/user/{username}", true] = async (parameters, ct) => { var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Path); Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'DeleteUser'"); - service.DeleteUser(Context, username); + await service.DeleteUser(Context, username); return new Response { ContentType = "application/xml"}; }; - Get["/user/{username}"] = parameters => + Get["/user/{username}", true] = async (parameters, ct) => { var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Path); Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'GetUserByName'"); - return service.GetUserByName(Context, username); + return await service.GetUserByName(Context, username); }; - Get["/user/login"] = parameters => + Get["/user/login", true] = async (parameters, ct) => { var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Query); var password = Parameters.ValueOf(parameters, Context.Request, "password", ParameterType.Query); @@ -74,17 +74,17 @@ public UserModule(UserService service) : base("/v2") Preconditions.IsNotNull(password, "Required parameter: 'password' is missing at 'LoginUser'"); - return service.LoginUser(Context, username, password); + return await service.LoginUser(Context, username, password); }; - Get["/user/logout"] = parameters => + Get["/user/logout", true] = async (parameters, ct) => { - service.LogoutUser(Context); + await service.LogoutUser(Context); return new Response { ContentType = "application/xml"}; }; - Put["/user/{username}"] = parameters => + Put["/user/{username}", true] = async (parameters, ct) => { var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Path); var body = this.Bind(); @@ -92,7 +92,7 @@ public UserModule(UserService service) : base("/v2") Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdateUser'"); - service.UpdateUser(Context, username, body); + await service.UpdateUser(Context, username, body); return new Response { ContentType = "application/xml"}; }; } @@ -109,7 +109,7 @@ public interface UserService /// Context of request /// Created user object /// - void CreateUser(NancyContext context, User body); + Task CreateUser(NancyContext context, User body); /// /// @@ -117,7 +117,7 @@ public interface UserService /// Context of request /// List of user object /// - void CreateUsersWithArrayInput(NancyContext context, List body); + Task CreateUsersWithArrayInput(NancyContext context, List body); /// /// @@ -125,7 +125,7 @@ public interface UserService /// Context of request /// List of user object /// - void CreateUsersWithListInput(NancyContext context, List body); + Task CreateUsersWithListInput(NancyContext context, List body); /// /// This can only be done by the logged in user. @@ -133,7 +133,7 @@ public interface UserService /// Context of request /// The name that needs to be deleted /// - void DeleteUser(NancyContext context, string username); + Task DeleteUser(NancyContext context, string username); /// /// @@ -141,7 +141,7 @@ public interface UserService /// Context of request /// The name that needs to be fetched. Use user1 for testing. /// User - User GetUserByName(NancyContext context, string username); + Task GetUserByName(NancyContext context, string username); /// /// @@ -150,14 +150,14 @@ public interface UserService /// The user name for login /// The password for login in clear text /// string - string LoginUser(NancyContext context, string username, string password); + Task LoginUser(NancyContext context, string username, string password); /// /// /// /// Context of request /// - void LogoutUser(NancyContext context); + Task LogoutUser(NancyContext context); /// /// This can only be done by the logged in user. @@ -166,7 +166,7 @@ public interface UserService /// name that need to be deleted /// Updated user object /// - void UpdateUser(NancyContext context, string username, User body); + Task UpdateUser(NancyContext context, string username, User body); } /// @@ -174,61 +174,61 @@ public interface UserService /// public abstract class AbstractUserService: UserService { - public virtual void CreateUser(NancyContext context, User body) + public virtual Task CreateUser(NancyContext context, User body) { - CreateUser(body); + return CreateUser(body); } - public virtual void CreateUsersWithArrayInput(NancyContext context, List body) + public virtual Task CreateUsersWithArrayInput(NancyContext context, List body) { - CreateUsersWithArrayInput(body); + return CreateUsersWithArrayInput(body); } - public virtual void CreateUsersWithListInput(NancyContext context, List body) + public virtual Task CreateUsersWithListInput(NancyContext context, List body) { - CreateUsersWithListInput(body); + return CreateUsersWithListInput(body); } - public virtual void DeleteUser(NancyContext context, string username) + public virtual Task DeleteUser(NancyContext context, string username) { - DeleteUser(username); + return DeleteUser(username); } - public virtual User GetUserByName(NancyContext context, string username) + public virtual Task GetUserByName(NancyContext context, string username) { return GetUserByName(username); } - public virtual string LoginUser(NancyContext context, string username, string password) + public virtual Task LoginUser(NancyContext context, string username, string password) { return LoginUser(username, password); } - public virtual void LogoutUser(NancyContext context) + public virtual Task LogoutUser(NancyContext context) { - LogoutUser(); + return LogoutUser(); } - public virtual void UpdateUser(NancyContext context, string username, User body) + public virtual Task UpdateUser(NancyContext context, string username, User body) { - UpdateUser(username, body); + return UpdateUser(username, body); } - protected abstract void CreateUser(User body); + protected abstract Task CreateUser(User body); - protected abstract void CreateUsersWithArrayInput(List body); + protected abstract Task CreateUsersWithArrayInput(List body); - protected abstract void CreateUsersWithListInput(List body); + protected abstract Task CreateUsersWithListInput(List body); - protected abstract void DeleteUser(string username); + protected abstract Task DeleteUser(string username); - protected abstract User GetUserByName(string username); + protected abstract Task GetUserByName(string username); - protected abstract string LoginUser(string username, string password); + protected abstract Task LoginUser(string username, string password); - protected abstract void LogoutUser(); + protected abstract Task LogoutUser(); - protected abstract void UpdateUser(string username, User body); + protected abstract Task UpdateUser(string username, User body); } } From 839471f8b3f9c5c21093d389cc60537355f2e7f2 Mon Sep 17 00:00:00 2001 From: raffael Date: Wed, 25 Oct 2017 17:47:05 +0200 Subject: [PATCH 7/9] remove additional new line in api.mustache + add space after if --- .../io/swagger/codegen/languages/NancyFXServerCodegen.java | 2 +- .../swagger-codegen/src/main/resources/nancyfx/api.mustache | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java index 49401cb075a..38d196e863c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java @@ -133,7 +133,7 @@ public void processOpts() { setPackageGuid((String) additionalProperties.get(OPTIONAL_PROJECT_GUID)); } - if(additionalProperties.containsKey(ASYNC_SERVER)) { + if (additionalProperties.containsKey(ASYNC_SERVER)) { setAsyncServer(Boolean.parseBoolean((String)additionalProperties.get(ASYNC_SERVER))); } diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache index fec7f9ac3b8..21ee6fd90e8 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache @@ -5,8 +5,8 @@ using System.Collections.Generic; using Sharpility.Base; using {{packageName}}.{{packageContext}}.Models; using {{packageName}}.{{packageContext}}.Utils; -using NodaTime; -{{#asyncServer}}using System.Threading.Tasks;{{/asyncServer}} +using NodaTime;{{#asyncServer}} +using System.Threading.Tasks;{{/asyncServer}} {{#imports}}using {{import}}; {{/imports}} From 41ba4476c3580ff6926e09f5f820d64e85da7987 Mon Sep 17 00:00:00 2001 From: raffael Date: Wed, 25 Oct 2017 17:50:32 +0200 Subject: [PATCH 8/9] run ./bin/nancyfx-petstore-server.sh and ./bin/nancyfx-petstore-server-async.sh --- .../server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs | 1 - .../petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs | 1 - .../server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs | 1 - 3 files changed, 3 deletions(-) diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs index f27290da30b..edfa0ecac4a 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs @@ -7,7 +7,6 @@ using IO.Swagger.v2.Utils; using NodaTime; - namespace IO.Swagger.v2.Modules { /// diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs index 17525f5c6bb..e5eed7a2485 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs @@ -7,7 +7,6 @@ using IO.Swagger.v2.Utils; using NodaTime; - namespace IO.Swagger.v2.Modules { diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs index 3abe9a8fc14..978013f17bb 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs @@ -7,7 +7,6 @@ using IO.Swagger.v2.Utils; using NodaTime; - namespace IO.Swagger.v2.Modules { From 5ac47cffa8c90c3121b3c45ff1bf70c05f72c4b5 Mon Sep 17 00:00:00 2001 From: raffael Date: Wed, 22 Nov 2017 14:53:42 +0100 Subject: [PATCH 9/9] Map `date` fields to LocalDate c# type + add a JsonConverter for LocalDate. --- .../languages/NancyFXServerCodegen.java | 5 +- .../nancyfx/localDateConverter.mustache | 55 +++++++++++++++++++ .../resources/nancyfx/parameters.mustache | 7 +++ .../src/IO.Swagger/Modules/PetModule.cs | 6 +- .../IO.Swagger/Utils/LocalDateConverter.cs | 55 +++++++++++++++++++ .../src/IO.Swagger/Utils/Parameters.cs | 7 +++ .../src/IO.Swagger/Modules/PetModule.cs | 6 +- .../IO.Swagger/Utils/LocalDateConverter.cs | 55 +++++++++++++++++++ .../src/IO.Swagger/Utils/Parameters.cs | 7 +++ 9 files changed, 195 insertions(+), 8 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/nancyfx/localDateConverter.mustache create mode 100644 samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/LocalDateConverter.cs create mode 100644 samples/server/petstore/nancyfx/src/IO.Swagger/Utils/LocalDateConverter.cs diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java index 70fd5dcbbeb..8acdbe5cb97 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java @@ -121,6 +121,7 @@ public void processOpts() { modelPackage = isNullOrEmpty(packageName) ? MODEL_NAMESPACE : packageName + "." + MODEL_NAMESPACE; supportingFiles.add(new SupportingFile("parameters.mustache", sourceFile("Utils"), "Parameters.cs")); + supportingFiles.add(new SupportingFile("localDateConverter.mustache", sourceFile("Utils"), "LocalDateConverter.cs")); supportingFiles.add(new SupportingFile("packages.config.mustache", sourceFolder(), "packages.config")); supportingFiles.add(new SupportingFile("nuspec.mustache", sourceFolder(), packageName + ".nuspec")); @@ -391,12 +392,12 @@ public boolean apply(Property property) { private static Map nodaTimeTypesMappings() { return ImmutableMap.of( "time", "LocalTime?", - "date", "ZonedDateTime?", + "date", "LocalDate?", "datetime", "ZonedDateTime?"); } private static Set nodaTimePrimitiveTypes() { - return ImmutableSet.of("LocalTime?", "ZonedDateTime?"); + return ImmutableSet.of("LocalTime?", "LocalDate?","ZonedDateTime?"); } private class DependencyInfo { diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/localDateConverter.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/localDateConverter.mustache new file mode 100644 index 00000000000..f8495d6fadd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/nancyfx/localDateConverter.mustache @@ -0,0 +1,55 @@ +using Nancy.Bootstrapper; +using Nancy.Json; +using NodaTime; +using NodaTime.Text; +using System; +using System.Collections.Generic; + +namespace {{packageName}}.{{packageContext}}.Utils +{ + /// + /// (De)serializes a to a string using + /// the RFC3339 + /// full-date format. + /// + public class LocalDateConverter : JavaScriptPrimitiveConverter, IApplicationStartup + { + public override IEnumerable SupportedTypes + { + get + { + yield return typeof(LocalDate); + yield return typeof(LocalDate?); + } + } + + public void Initialize(IPipelines pipelines) + { + JsonSettings.PrimitiveConverters.Add(new LocalDateConverter()); + } + + + public override object Serialize(object obj, JavaScriptSerializer serializer) + { + if (obj is LocalDate) + { + LocalDate localDate = (LocalDate)obj; + return LocalDatePattern.IsoPattern.Format(localDate); + } + return null; + } + + public override object Deserialize(object primitiveValue, Type type, JavaScriptSerializer serializer) + { + if ((type == typeof(LocalDate) || type == typeof(LocalDate?)) && primitiveValue is string) + { + try + { + return LocalDatePattern.IsoPattern.Parse(primitiveValue as string).GetValueOrThrow(); + } + catch { } + } + return null; + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/parameters.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/parameters.mustache index 75486f59f46..f760dfec75f 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/parameters.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/parameters.mustache @@ -163,6 +163,8 @@ namespace {{packageName}}.{{packageContext}}.Utils parsers.Put(typeof(TimeSpan?), SafeParse(TimeSpan.Parse)); parsers.Put(typeof(ZonedDateTime), SafeParse(ParseZonedDateTime)); parsers.Put(typeof(ZonedDateTime?), SafeParse(ParseZonedDateTime)); + parsers.Put(typeof(LocalDate), SafeParse(ParseLocalDate)); + parsers.Put(typeof(LocalDate?), SafeParse(ParseLocalDate)); parsers.Put(typeof(LocalTime), SafeParse(ParseLocalTime)); parsers.Put(typeof(LocalTime?), SafeParse(ParseLocalTime)); @@ -372,6 +374,11 @@ namespace {{packageName}}.{{packageContext}}.Utils return new ZonedDateTime(Instant.FromDateTimeUtc(dateTime.ToUniversalTime()), DateTimeZone.Utc); } + private static LocalDate ParseLocalDate(string value) + { + return LocalDatePattern.IsoPattern.Parse(value).Value; + } + private static LocalTime ParseLocalTime(string value) { return LocalTimePattern.ExtendedIsoPattern.Parse(value).Value; diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs index 0d4cf8616c7..6b3e8cc1db8 100644 --- a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Modules/PetModule.cs @@ -15,9 +15,9 @@ namespace IO.Swagger.v2.Modules /// public enum FindPetsByStatusStatusEnum { - available, - pending, - sold + available = 1, + pending = 2, + sold = 3 }; diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/LocalDateConverter.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/LocalDateConverter.cs new file mode 100644 index 00000000000..d801e962c6a --- /dev/null +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/LocalDateConverter.cs @@ -0,0 +1,55 @@ +using Nancy.Bootstrapper; +using Nancy.Json; +using NodaTime; +using NodaTime.Text; +using System; +using System.Collections.Generic; + +namespace IO.Swagger.v2.Utils +{ + /// + /// (De)serializes a to a string using + /// the RFC3339 + /// full-date format. + /// + public class LocalDateConverter : JavaScriptPrimitiveConverter, IApplicationStartup + { + public override IEnumerable SupportedTypes + { + get + { + yield return typeof(LocalDate); + yield return typeof(LocalDate?); + } + } + + public void Initialize(IPipelines pipelines) + { + JsonSettings.PrimitiveConverters.Add(new LocalDateConverter()); + } + + + public override object Serialize(object obj, JavaScriptSerializer serializer) + { + if (obj is LocalDate) + { + LocalDate localDate = (LocalDate)obj; + return LocalDatePattern.IsoPattern.Format(localDate); + } + return null; + } + + public override object Deserialize(object primitiveValue, Type type, JavaScriptSerializer serializer) + { + if ((type == typeof(LocalDate) || type == typeof(LocalDate?)) && primitiveValue is string) + { + try + { + return LocalDatePattern.IsoPattern.Parse(primitiveValue as string).GetValueOrThrow(); + } + catch { } + } + return null; + } + } +} diff --git a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/Parameters.cs b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/Parameters.cs index 6175758fd9a..d2198945763 100644 --- a/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/Parameters.cs +++ b/samples/server/petstore/nancyfx-async/src/IO.Swagger/Utils/Parameters.cs @@ -163,6 +163,8 @@ private static IDictionary> CreateParsers() parsers.Put(typeof(TimeSpan?), SafeParse(TimeSpan.Parse)); parsers.Put(typeof(ZonedDateTime), SafeParse(ParseZonedDateTime)); parsers.Put(typeof(ZonedDateTime?), SafeParse(ParseZonedDateTime)); + parsers.Put(typeof(LocalDate), SafeParse(ParseLocalDate)); + parsers.Put(typeof(LocalDate?), SafeParse(ParseLocalDate)); parsers.Put(typeof(LocalTime), SafeParse(ParseLocalTime)); parsers.Put(typeof(LocalTime?), SafeParse(ParseLocalTime)); @@ -372,6 +374,11 @@ private static ZonedDateTime ParseZonedDateTime(string value) return new ZonedDateTime(Instant.FromDateTimeUtc(dateTime.ToUniversalTime()), DateTimeZone.Utc); } + private static LocalDate ParseLocalDate(string value) + { + return LocalDatePattern.IsoPattern.Parse(value).Value; + } + private static LocalTime ParseLocalTime(string value) { return LocalTimePattern.ExtendedIsoPattern.Parse(value).Value; diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs index edfa0ecac4a..2e5d229cdfe 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs @@ -14,9 +14,9 @@ namespace IO.Swagger.v2.Modules /// public enum FindPetsByStatusStatusEnum { - available, - pending, - sold + available = 1, + pending = 2, + sold = 3 }; diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Utils/LocalDateConverter.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Utils/LocalDateConverter.cs new file mode 100644 index 00000000000..d801e962c6a --- /dev/null +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Utils/LocalDateConverter.cs @@ -0,0 +1,55 @@ +using Nancy.Bootstrapper; +using Nancy.Json; +using NodaTime; +using NodaTime.Text; +using System; +using System.Collections.Generic; + +namespace IO.Swagger.v2.Utils +{ + /// + /// (De)serializes a to a string using + /// the RFC3339 + /// full-date format. + /// + public class LocalDateConverter : JavaScriptPrimitiveConverter, IApplicationStartup + { + public override IEnumerable SupportedTypes + { + get + { + yield return typeof(LocalDate); + yield return typeof(LocalDate?); + } + } + + public void Initialize(IPipelines pipelines) + { + JsonSettings.PrimitiveConverters.Add(new LocalDateConverter()); + } + + + public override object Serialize(object obj, JavaScriptSerializer serializer) + { + if (obj is LocalDate) + { + LocalDate localDate = (LocalDate)obj; + return LocalDatePattern.IsoPattern.Format(localDate); + } + return null; + } + + public override object Deserialize(object primitiveValue, Type type, JavaScriptSerializer serializer) + { + if ((type == typeof(LocalDate) || type == typeof(LocalDate?)) && primitiveValue is string) + { + try + { + return LocalDatePattern.IsoPattern.Parse(primitiveValue as string).GetValueOrThrow(); + } + catch { } + } + return null; + } + } +} diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Utils/Parameters.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Utils/Parameters.cs index 6175758fd9a..d2198945763 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Utils/Parameters.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Utils/Parameters.cs @@ -163,6 +163,8 @@ private static IDictionary> CreateParsers() parsers.Put(typeof(TimeSpan?), SafeParse(TimeSpan.Parse)); parsers.Put(typeof(ZonedDateTime), SafeParse(ParseZonedDateTime)); parsers.Put(typeof(ZonedDateTime?), SafeParse(ParseZonedDateTime)); + parsers.Put(typeof(LocalDate), SafeParse(ParseLocalDate)); + parsers.Put(typeof(LocalDate?), SafeParse(ParseLocalDate)); parsers.Put(typeof(LocalTime), SafeParse(ParseLocalTime)); parsers.Put(typeof(LocalTime?), SafeParse(ParseLocalTime)); @@ -372,6 +374,11 @@ private static ZonedDateTime ParseZonedDateTime(string value) return new ZonedDateTime(Instant.FromDateTimeUtc(dateTime.ToUniversalTime()), DateTimeZone.Utc); } + private static LocalDate ParseLocalDate(string value) + { + return LocalDatePattern.IsoPattern.Parse(value).Value; + } + private static LocalTime ParseLocalTime(string value) { return LocalTimePattern.ExtendedIsoPattern.Parse(value).Value;