Example #1
0
        /// <summary>Deserializes a JSON string to a <see cref="JsonSchema4" />.</summary>
        /// <param name="data">The JSON string.</param>
        /// <param name="documentPath">The document path (URL or file path) for resolving relative document references.</param>
        /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
        /// <returns>The JSON Schema.</returns>
        public static async Task <JsonSchema4> FromJsonAsync(string data, string documentPath, Func <JsonSchema4, JsonReferenceResolver> referenceResolverFactory)
        {
            var schemaType       = SchemaType.JsonSchema;
            var contractResolver = CreateJsonSerializerContractResolver(schemaType);

            return(await JsonSchemaSerialization.FromJsonAsync(data, schemaType, documentPath, referenceResolverFactory, contractResolver));
        }
Example #2
0
        public async Task When_inheritance_with_object_without_props_is_generated_then_all_classes_exist_and_additional_properties_property_is_not_generated()
        {
            // Arrange
            var json = @"{
  ""type"": ""object"",
  ""properties"": {
    ""Exception"": {
      ""$ref"": ""#/definitions/BusinessException""
    }
  },
  ""additionalProperties"": false,
  ""definitions"": {
    ""BusinessException"": {
      ""type"": ""object"",
      ""additionalProperties"": false,
      ""properties"": {
        ""customerId"": {
          ""type"": ""string"",
          ""nullable"": true
        },
        ""customerAlias"": {
          ""type"": ""string"",
          ""nullable"": true
        },
        ""userId"": {
          ""type"": ""string"",
          ""nullable"": true
        }
      }
    },
    ""ValidationException"": {
      ""allOf"": [
        {
          ""$ref"": ""#/definitions/BusinessException""
        },
        {
          ""type"": ""object"",
          ""additionalProperties"": false
        }
      ]
    }
  }
}";

            var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator());
            var schema  = await JsonSchemaSerialization.FromJsonAsync(json, SchemaType.OpenApi3, null, factory, new DefaultContractResolver());

            // Act
            var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings {
                SchemaType = SchemaType.OpenApi3
            });
            var code = generator.GenerateFile("MyClass");

            //// Act
            Assert.Contains("class BusinessException", code);
            Assert.Contains("class ValidationException", code);
            Assert.DoesNotContain("AdditionalProperties", code);
        }
        public async Task When_schema_JSON_is_deserialized_then_AllowAdditionalProperties_is_correct(SchemaType schemaType, string json, bool expectedAllowAdditionalProperties)
        {
            //// Act
            var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator());
            var schema  = await JsonSchemaSerialization.FromJsonAsync(json, schemaType, null, factory, new DefaultContractResolver());

            //// Assert
            Assert.Equal(expectedAllowAdditionalProperties, schema.AllowAdditionalProperties);
        }
Example #4
0
        /// <summary>Creates a Swagger specification from a JSON string.</summary>
        /// <param name="data">The JSON data.</param>
        /// <param name="documentPath">The document path (URL or file path) for resolving relative document references.</param>
        /// <param name="expectedSchemaType">The expected schema type which is used when the type cannot be determined.</param>
        /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The <see cref="OpenApiDocument"/>.</returns>
        public static async Task <OpenApiDocument> FromJsonAsync(string data, string documentPath, SchemaType expectedSchemaType,
                                                                 Func <OpenApiDocument, JsonReferenceResolver> referenceResolverFactory, CancellationToken cancellationToken = default)
        {
            // For explanation of the regex use https://regexr.com/ and the below unescaped pattern that is without named groups
            // (?:\"(openapi|swagger)\")(?:\s*:\s*)(?:\"([^"]*)\")
            var pattern = "(?:\\\"(?<schemaType>openapi|swagger)\\\")(?:\\s*:\\s*)(?:\\\"(?<schemaVersion>[^\"]*)\\\")";
            var match   = Regex.Match(data, pattern, RegexOptions.IgnoreCase);

            if (match.Success)
            {
                var schemaType    = match.Groups["schemaType"].Value.ToLower();
                var schemaVersion = match.Groups["schemaVersion"].Value.ToLower();

                if (schemaType == "swagger" && schemaVersion.StartsWith("2"))
                {
                    expectedSchemaType = SchemaType.Swagger2;
                }
                else if (schemaType == "openapi" && schemaVersion.StartsWith("3"))
                {
                    expectedSchemaType = SchemaType.OpenApi3;
                }
            }

            if (expectedSchemaType == SchemaType.JsonSchema)
            {
                throw new NotSupportedException("The schema type JsonSchema is not supported.");
            }

            var contractResolver = GetJsonSerializerContractResolver(expectedSchemaType);

            return(await JsonSchemaSerialization.FromJsonAsync <OpenApiDocument>(data, expectedSchemaType, documentPath, document =>
            {
                document.SchemaType = expectedSchemaType;
                if (referenceResolverFactory != null)
                {
                    return referenceResolverFactory(document);
                }
                else
                {
                    var schemaResolver = new OpenApiSchemaResolver(document, new JsonSchemaGeneratorSettings());
                    return new JsonReferenceResolver(schemaResolver);
                }
            }, contractResolver, cancellationToken).ConfigureAwait(false));
        }
Example #5
0
        public async Task When_date_reference_is_generated_from_swagger2_schema_then_generated_member_is_decorated_with_date_format_attribute()
        {
            // Arrange
            var json = @"{
  ""type"": ""object"",
  ""properties"": {
    ""MyType"": {
      ""$ref"": ""#/definitions/MyType""
    }
  },
  ""additionalProperties"": false,
	""definitions"": {
		""MyType"": {
			""type"": ""object"",
			""required"": [
				""EntryDate"",
			],
			""properties"": {
			    ""EntryDate"": {
				    ""$ref"": ""#/definitions/EntryDate""
				}
			}
		},
		""EntryDate"": {
			""example"": ""2020-08-28"",
			""type"": ""string"",
			""format"": ""date""
		}
	}
}";

            var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator());
            var schema  = await JsonSchemaSerialization.FromJsonAsync(json, SchemaType.Swagger2, null, factory, new DefaultContractResolver());

            // Act
            var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings {
                SchemaType = SchemaType.Swagger2
            });
            var code = generator.GenerateFile("MyClass");

            //// Act
            Assert.Contains("[Newtonsoft.Json.JsonConverter(typeof(DateFormatConverter))]", code);
        }
Example #6
0
        /// <summary>Creates a Swagger specification from a JSON string.</summary>
        /// <param name="data">The JSON data.</param>
        /// <param name="documentPath">The document path (URL or file path) for resolving relative document references.</param>
        /// <param name="expectedSchemaType">The expected schema type which is used when the type cannot be determined.</param>
        /// <returns>The <see cref="SwaggerDocument"/>.</returns>
        public static async Task <SwaggerDocument> FromJsonAsync(string data, string documentPath = null, SchemaType expectedSchemaType = SchemaType.Swagger2)
        {
            if (data.Contains(@"""swagger"": ""2"))
            {
                expectedSchemaType = SchemaType.Swagger2;
            }
            else if (data.Contains(@"""openapi"": ""3"))
            {
                expectedSchemaType = SchemaType.OpenApi3;
            }
            else if (expectedSchemaType == SchemaType.JsonSchema)
            {
                throw new NotSupportedException("The schema type JsonSchema is not supported.");
            }

            var contractResolver = CreateJsonSerializerContractResolver(expectedSchemaType);

            return(await JsonSchemaSerialization.FromJsonAsync <SwaggerDocument>(data, expectedSchemaType, documentPath, document =>
            {
                var schemaResolver = new SwaggerSchemaResolver(document, new JsonSchemaGeneratorSettings());
                return new JsonReferenceResolver(schemaResolver);
            }, contractResolver).ConfigureAwait(false));
        }
Example #7
0
 /// <summary>Deserializes a JSON string to a <see cref="JsonSchema" />.</summary>
 /// <param name="data">The JSON string.</param>
 /// <param name="documentPath">The document path (URL or file path) for resolving relative document references.</param>
 /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
 /// <param name="cancellationToken">The cancellation token</param>
 /// <returns>The JSON Schema.</returns>
 public static async Task <JsonSchema> FromJsonAsync(string data, string documentPath, Func <JsonSchema,
                                                                                             JsonReferenceResolver> referenceResolverFactory, CancellationToken cancellationToken = default)
 {
     return(await JsonSchemaSerialization.FromJsonAsync(data, SerializationSchemaType, documentPath, referenceResolverFactory, ContractResolver.Value, cancellationToken).ConfigureAwait(false));
 }
Example #8
0
 /// <summary>Deserializes a JSON string to a <see cref="JsonSchema4" />.</summary>
 /// <param name="data">The JSON string.</param>
 /// <param name="documentPath">The document path (URL or file path) for resolving relative document references.</param>
 /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
 /// <returns>The JSON Schema.</returns>
 public static async Task <JsonSchema4> FromJsonAsync(string data, string documentPath, Func <JsonSchema4, JsonReferenceResolver> referenceResolverFactory)
 {
     return(await JsonSchemaSerialization.FromJsonAsync(data, SerializationSchemaType, documentPath, referenceResolverFactory, ContractResolver.Value));
 }
Example #9
0
        public async Task When_schema_with_inheritance_and_references_is_generated_then_there_are_no_duplicates(SchemaType schemaType)
        {
            var json = @"
{
    ""type"": ""object"",
    ""properties"": {
        ""foo"": {
            ""$ref"": ""#/definitions/Teacher""
        }
    },
    ""definitions"": {
        ""Person"": {
            ""type"": ""object"",
            ""discriminator"": ""discriminator"",
            ""required"": [
                ""discriminator""
            ],
            ""properties"": {
                ""Skills"": {
                    ""type"": ""object"",
                    ""additionalProperties"": {
                        ""$ref"": ""#/definitions/SkillLevel""
                    }
                },
                ""discriminator"": {
                    ""type"": ""string""
                }
            }
        },
        ""SkillLevel"": {
            ""type"": ""integer"",
            ""description"": """",
            ""x-enumNames"": [
                ""Low"",
                ""Medium"",
                ""Height""
            ],
            ""enum"": [
                0,
                1,
                2
            ]
        },
        ""Teacher"": {
            ""allOf"": [
                {
                    ""$ref"": ""#/definitions/Person""
                },
                {
                    ""type"": ""object"",
                    ""required"": [
                        ""SkillLevel""
                    ],
                    ""properties"": {
                        ""Course"": {
                            ""type"": ""string""
                        },
                        ""SkillLevel"": {
                            ""default"": 1,
                            ""allOf"": [
                                {
                                    ""$ref"": ""#/definitions/SkillLevel""
                                }
                            ]
                        }
                    }
                }
            ]
        }
    }
}
";

            var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator());
            var schema  = await JsonSchemaSerialization.FromJsonAsync(json, schemaType, null, factory, new DefaultContractResolver());

            var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings {
                TypeScriptVersion = 2.0m, SchemaType = schemaType
            });

            //// Act
            var code = generator.GenerateFile();

            //// Assert
            Assert.DoesNotContain("SkillLevel2", code);
        }
Example #10
0
        public async Task When_schema_with_inheritance_to_object_type_is_generated_then_the_object_type_is_generated(SchemaType schemaType)
        {
            var json = @"{
    ""type"": ""object"",
    ""properties"": {
        ""request1"": {
            ""$ref"": ""#/definitions/GenericRequest1""
        },
        ""request2"": {
            ""$ref"": ""#/definitions/GenericRequest2""
        }
    },
    ""definitions"": {
        ""GenericRequest1"": {
            ""allOf"": [
                {
                    ""$ref"": ""#/definitions/GenericRequestBaseOfRequestBodyBase""
                },
                {
                    ""type"": ""object""
                }
            ]
        },
        ""GenericRequestBaseOfRequestBodyBase"": {
            ""type"": ""object"",
            ""required"": [
                ""Request""
            ],
            ""properties"": {
                ""Request"": {
                    ""$ref"": ""#/definitions/RequestBodyBase""
                }
            }
        },
        ""RequestBodyBase"": {
            ""type"": ""object""
        },
        ""GenericRequest2"": {
            ""allOf"": [
                {
                    ""$ref"": ""#/definitions/GenericRequestBaseOfRequestBody""
                },
                {
                    ""type"": ""object""
                }
            ]
        },
        ""GenericRequestBaseOfRequestBody"": {
            ""type"": ""object"",
            ""required"": [
                ""Request""
            ],
            ""properties"": {
                ""Request"": {
                    ""$ref"": ""#/definitions/RequestBody""
                }
            }
        },
        ""RequestBody"": {
            ""allOf"": [
                {
                    ""$ref"": ""#/definitions/RequestBodyBase""
                },
                {
                    ""type"": ""object""
                }
            ]
        }
    }
}";

            var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator());
            var schema  = await JsonSchemaSerialization.FromJsonAsync(json, schemaType, null, factory, new DefaultContractResolver());

            var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings {
                TypeScriptVersion = 2.0m, SchemaType = schemaType
            });

            //// Act
            var code = generator.GenerateFile();

            //// Assert
            Assert.DoesNotContain("request!: any;", code);
            Assert.DoesNotContain("request: any;", code);
            Assert.Contains("this.request = new RequestBodyBase()", code);
            Assert.Contains("this.request = new RequestBody()", code);
        }