Example #1
0
        public async Task WhenSpecContainsFormDataInNestedMultipartForm_ThenFormDataIsUsedInTypeScript()
        {
            var json = @"{
  ""x-generator"": ""NSwag v13.5.0.0 (NJsonSchema v10.1.15.0 (Newtonsoft.Json v11.0.0.0))"",
  ""openapi"": ""3.0.0"",
  ""info"": {
    ""title"": ""My Title"",
    ""version"": ""1.0.0""
  },
  ""paths"": {
    ""/api/FileUpload/UploadAttachment"": {
      ""post"": {
        ""tags"": [
          ""FileUpload""
        ],
        ""operationId"": ""FileUpload_UploadAttachment"",
        ""parameters"": [
          {
            ""name"": ""caseId"",
            ""in"": ""path"",
            ""required"": true,
            ""schema"": {
              ""type"": ""string"",
              ""nullable"": true
            },
            ""x-position"": 1
          }
        ],
        ""requestBody"": {
          ""content"": {
            ""multipart/form-data"": {
              ""schema"": {
                ""properties"": {
                  ""Description"": {
                    ""type"": ""string"",
                    ""nullable"": true
                  },
                  ""Contents"": {
                    ""type"": ""string"",
                    ""format"": ""binary"",
                    ""nullable"": true
                  }
                }
              }
            }
          }
        },
        ""responses"": {
          ""200"": {
            ""description"": """",
            ""content"": {
              ""application/octet-stream"": {
                ""schema"": {
                  ""type"": ""string"",
                  ""format"": ""binary""
                }
              }
            }
          }
        }
      }
    }
  },
  ""components"": {}
}";

            var document = await OpenApiDocument.FromJsonAsync(json);

            //// Act
            var codeGenerator = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings());
            var code          = codeGenerator.GenerateFile();

            //// Assert
            Assert.Contains("const content_ = new FormData();", code);
            Assert.Contains("interface FileParameter", code);
            Assert.Contains("content_.append(\"Contents\", contents.data, contents.fileName ? contents.fileName : \"Contents\");", code);
        }
Example #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireNonAlphanumeric = false;
            });

            services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));
            services.AddDbContext <UnderSeaDatabaseContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity <User>()
            .AddEntityFrameworkStores <UnderSeaDatabaseContext>();

            services.AddIdentityServer()
            .AddCorsPolicyService <IdentityServerCorsPolicyService>()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources(Configuration))
            .AddInMemoryClients(IdentityServerConfig.GetClients(Configuration))
            .AddAspNetIdentity <User>();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Authority                 = Configuration["Authority"];
                options.Audience                  = Configuration["ApiName"];
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    NameClaimType = JwtClaimTypes.Name
                };
            });

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(policy =>
                {
                    policy.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSignalR();

            services.AddSwaggerDocument(options =>
            {
                options.Title       = "Undersea API";
                options.Version     = "1.0";
                options.Description = "API for the game called Under sea, which is a turn based online multiplayer strategy game.";

                options.PostProcess = document =>
                {
                    var settings = new TypeScriptClientGeneratorSettings
                    {
                        ClassName = "{controller}Client",
                        Template  = TypeScriptTemplate.Axios
                    };

                    var generator = new TypeScriptClientGenerator(document, settings);
                    var code      = generator.GenerateFile();

                    var path      = Directory.GetCurrentDirectory();
                    var directory = new DirectoryInfo(path + @"\TypeScript");
                    if (!directory.Exists)
                    {
                        directory.Create();
                    }

                    var filePath = path + @"\TypeScript\Client.ts";
                    File.WriteAllText(filePath, code);
                };
            });

            services.AddAutoMapper(typeof(KnownValues).Assembly);

            services.AddSingleton(new ModifierParserContainer(new AbstractEffectModifierParser[]
            {
                new BarrackSpaceEffectParser(),
                new CoralProductionEffectParser(),
                new PearlProductionEffectParser(),
                new HarvestModifierEffectParser(),
                new PopulationEffectParser(),
                new TaxModifierEffectParser(),
                new UnitDefenseEffectParser(),
                new UnitAttackEffectParser(),
                new AddBuildingEffectParser(),
                new IncreaseUnitAttackEffectParser(),
                new BuildingCoralProductionEffectParser()
            }));

            services.AddSingleton <IUserTracker, UserTracker>();

            services.AddTransient <ITurnHandlingService, TurnHandlingService>();
            services.AddTransient <ICountryService, CountryService>();
            services.AddTransient <IResearchService, ResearchService>();
            services.AddTransient <IBuildingService, BuildingService>();
            services.AddTransient <IUnitService, UnitService>();
            services.AddTransient <ICommandService, CommandService>();
            services.AddTransient <IExceptionLogger, ExceptionLogger>();

            // User ID provider for SignalR Hub
            services.AddTransient <IUserIdProvider, UserIdProvider>();
        }
Example #3
0
        public async Task when_content_is_formdata_with_property_array_then_content_should_be_added_in_foreach_in_typescript()
        {
            var json = @"{
              ""x-generator"": ""NSwag v13.5.0.0 (NJsonSchema v10.1.15.0 (Newtonsoft.Json v11.0.0.0))"",
              ""openapi"": ""3.0.0"",
              ""info"": {
                ""title"": ""My Title"",
                ""version"": ""1.0.0""
              },
              ""paths"": {
                ""/api/FileUpload/UploadFile"": {
                  ""post"": {
                    ""tags"": [
                      ""FileUpload""
                    ],
                    ""operationId"": ""FileUpload_UploadFile"",
                    ""requestBody"": {
                      ""content"": {
                        ""multipart/form-data"": {
                          ""schema"": {
                            ""properties"": {
                              ""file"": {
                                ""type"": ""string"",
                                ""format"": ""binary""
                              },
                              ""arrayOfIds"": {
                                ""uniqueItems"": true,
                                ""type"": ""array"",
                                ""items"": {
                                  ""type"": ""string""
                                },
                                ""description"": ""Hash Set of of strings in the DTO request"",
                                ""nullable"": true
                              },
                              ""test"": {
                                ""type"": ""string""
                              }
                            }
                          }
                        }
                      }
                    },
                    ""responses"": {
                      ""200"": {
                        ""description"": """",
                        ""content"": {
                          ""application/octet-stream"": {
                            ""schema"": {
                              ""type"": ""string"",
                              ""format"": ""binary""
                            }
                          }
                        }
                      }
                    }
                  }
                },
    
              },
              ""components"": {}
            }";

            var document = await OpenApiDocument.FromJsonAsync(json);

            // Act
            var codeGenerator = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings());
            var code          = codeGenerator.GenerateFile();

            // Assert
            Assert.Contains("const content_ = new FormData();", code);
            Assert.Contains("arrayOfIds.forEach(item_ => content_.append(\"arrayOfIds\", item_.toString()));", code);
        }
Example #4
0
        public async Task When_parameter_is_array_then_TypeScript_is_correct()
        {
            // Arrange
            var swagger  = @"{
  ""swagger"" : ""2.0"",
  ""info"" : {
    ""version"" : ""1.0.2"",
    ""title"" : ""Test API""
  },
  ""host"" : ""localhost:8080"",
  ""basePath"" : ""/"",
  ""tags"" : [ {
    ""name"" : ""api""
  } ],
  ""schemes"" : [ ""http"" ],
  ""paths"" : {
     ""/removeElement"" : {
      ""delete"" : {
        ""tags"" : [ ""api"" ],
        ""summary"" : ""Removes elements"",
        ""description"" : ""Removes elements"",
        ""operationId"" : ""removeElement"",
        ""consumes"" : [ ""application/json"" ],
        ""produces"" : [ ""application/json"" ],
        ""parameters"" : [ {
          ""name"" : ""X-User"",
          ""in"" : ""header"",
          ""description"" : ""User identifier"",
          ""required"" : true,
          ""type"" : ""string""
        }, {
          ""name"" : ""elementId"",
          ""in"" : ""query"",
          ""description"" : ""The ids of existing elements that should be removed"",
          ""required"" : false,
          ""type"" : ""array"",
          ""items"" : {
            ""type"" : ""integer"",
            ""format"" : ""int64""
          },
        } ],
        ""responses"" : {
          ""default"" : {
            ""description"" : ""successful operation""
          }
        }
      }
    }
  },
    ""definitions"" : { }
}
";
            var document = await OpenApiDocument.FromJsonAsync(swagger);

            // Act
            var settings = new TypeScriptClientGeneratorSettings {
                ClassName = "MyClass"
            };
            var generator = new TypeScriptClientGenerator(document, settings);
            var code      = generator.GenerateFile();

            // Assert
            Assert.Contains(@"elementId.forEach(item => { url_ += ""elementId="" + encodeURIComponent("""" + item) + ""&""; });", code);
        }
Example #5
0
        public async Task when_content_is_formdata_with_property_object_then_content_should_be_json_typescript()
        {
            var json = @"{
              ""x-generator"": ""NSwag v13.5.0.0 (NJsonSchema v10.1.15.0 (Newtonsoft.Json v11.0.0.0))"",
              ""openapi"": ""3.0.0"",
              ""info"": {
                ""title"": ""My Title"",
                ""version"": ""1.0.0""
              },
              ""paths"": {
                ""/api/FileUpload/UploadFile"": {
                  ""post"": {
                    ""tags"": [
                      ""FileUpload""
                    ],
                    ""operationId"": ""FileUpload_UploadFile"",
                    ""requestBody"": {
                      ""content"": {
                        ""multipart/form-data"": {
                          ""schema"": {
                            ""properties"": {
                              ""file"": {
                                ""type"": ""string"",
                                ""format"": ""binary""
                              },
                              ""propertyDto"": {
                                ""type"": ""object"",
                                ""description"": ""Configurable properties""
                              },
                              ""test"": {
                                ""type"": ""string""
                              }
                            }
                          }
                        }
                      }
                    },
                    ""responses"": {
                      ""200"": {
                        ""description"": """",
                        ""content"": {
                          ""application/octet-stream"": {
                            ""schema"": {
                              ""type"": ""string"",
                              ""format"": ""binary""
                            }
                          }
                        }
                      }
                    }
                  }
                },
    
              },
              ""components"": {}
            }";

            var document = await OpenApiDocument.FromJsonAsync(json);

            //// Act
            var codeGenerator = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings());
            var code          = codeGenerator.GenerateFile();

            //// Assert
            Assert.Contains("const content_ = new FormData();", code);
            Assert.Contains("content_.append(\"propertyDto\", JSON.stringify(propertyDto))", code);
        }