Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for OpenAPI schema generation for POCOs #1094

Merged
merged 6 commits into from
Dec 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 130 additions & 0 deletions src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Models;

namespace Microsoft.OpenApi.Extensions
{
/// <summary>
/// Extension methods for <see cref="Type"/>.
/// </summary>
public static class OpenApiTypeMapper
{
private static readonly Dictionary<Type, Func<OpenApiSchema>> _simpleTypeToOpenApiSchema = new()
baywet marked this conversation as resolved.
Show resolved Hide resolved
{
[typeof(bool)] = () => new OpenApiSchema { Type = "boolean" },
[typeof(byte)] = () => new OpenApiSchema { Type = "string", Format = "byte" },
[typeof(int)] = () => new OpenApiSchema { Type = "integer", Format = "int32" },
[typeof(uint)] = () => new OpenApiSchema { Type = "integer", Format = "int32" },
[typeof(long)] = () => new OpenApiSchema { Type = "integer", Format = "int64" },
[typeof(ulong)] = () => new OpenApiSchema { Type = "integer", Format = "int64" },
[typeof(float)] = () => new OpenApiSchema { Type = "number", Format = "float" },
[typeof(double)] = () => new OpenApiSchema { Type = "number", Format = "double" },
[typeof(decimal)] = () => new OpenApiSchema { Type = "number", Format = "double" },
[typeof(DateTime)] = () => new OpenApiSchema { Type = "string", Format = "date-time" },
[typeof(DateTimeOffset)] = () => new OpenApiSchema { Type = "string", Format = "date-time" },
[typeof(Guid)] = () => new OpenApiSchema { Type = "string", Format = "uuid" },
[typeof(char)] = () => new OpenApiSchema { Type = "string" },

// Nullable types
[typeof(bool?)] = () => new OpenApiSchema { Type = "boolean", Nullable = true },
[typeof(byte?)] = () => new OpenApiSchema { Type = "string", Format = "byte", Nullable = true },
[typeof(int?)] = () => new OpenApiSchema { Type = "integer", Format = "int32", Nullable = true },
[typeof(uint?)] = () => new OpenApiSchema { Type = "integer", Format = "int32", Nullable = true },
[typeof(long?)] = () => new OpenApiSchema { Type = "integer", Format = "int64", Nullable = true },
[typeof(ulong?)] = () => new OpenApiSchema { Type = "integer", Format = "int64", Nullable = true },
[typeof(float?)] = () => new OpenApiSchema { Type = "number", Format = "float", Nullable = true },
[typeof(double?)] = () => new OpenApiSchema { Type = "number", Format = "double", Nullable = true },
[typeof(decimal?)] = () => new OpenApiSchema { Type = "number", Format = "double", Nullable = true },
[typeof(DateTime?)] = () => new OpenApiSchema { Type = "string", Format = "date-time", Nullable = true },
[typeof(DateTimeOffset?)] = () => new OpenApiSchema { Type = "string", Format = "date-time", Nullable = true },
[typeof(Guid?)] = () => new OpenApiSchema { Type = "string", Format = "uuid", Nullable = true },
MaggieKimani1 marked this conversation as resolved.
Show resolved Hide resolved
[typeof(char?)] = () => new OpenApiSchema { Type = "string", Nullable = true },

[typeof(Uri)] = () => new OpenApiSchema { Type = "string", Format = "uri"}, // Uri is treated as simple string
[typeof(string)] = () => new OpenApiSchema { Type = "string" },
[typeof(object)] = () => new OpenApiSchema { Type = "object" }
};

/// <summary>
/// Maps a simple type to an OpenAPI data type and format.
/// </summary>
/// <param name="type">Simple type.</param>
/// <remarks>
/// All the following types from http://swagger.io/specification/#data-types-12 are supported.
/// Other types including nullables and URL are also supported.
/// Common Name type format Comments
/// =========== ======= ====== =========================================
/// integer integer int32 signed 32 bits
/// long integer int64 signed 64 bits
/// float number float
/// double number double
/// string string [empty]
/// byte string byte base64 encoded characters
/// binary string binary any sequence of octets
/// boolean boolean [empty]
/// date string date As defined by full-date - RFC3339
/// dateTime string date-time As defined by date-time - RFC3339
/// password string password Used to hint UIs the input needs to be obscured.
/// If the type is not recognized as "simple", System.String will be returned.
/// </remarks>
public static OpenApiSchema MapTypeToOpenApiPrimitiveType(this Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}

return _simpleTypeToOpenApiSchema.TryGetValue(type, out var result)
? result()
: new OpenApiSchema { Type = "string" };
}

/// <summary>
/// Maps an OpenAPI data type and format to a simple type.
/// </summary>
/// <param name="schema">The OpenApi data type</param>
/// <returns>The simple type</returns>
/// <exception cref="ArgumentNullException"></exception>
public static Type MapOpenApiPrimitiveTypeToSimpleType(this OpenApiSchema schema)
{
if (schema == null)
{
throw new ArgumentNullException(nameof(schema));
}

var type = (schema.Type?.ToLowerInvariant(), schema.Format?.ToLowerInvariant(), schema.Nullable) switch
{
("boolean", null, false) => typeof(bool),
("integer", "int32", false) => typeof(int),
("integer", "int64", false) => typeof(long),
("number", "float", false) => typeof(float),
("number", "double", false) => typeof(double),
("number", "decimal", false) => typeof(decimal),
("string", "byte", false) => typeof(byte),
("string", "date-time", false) => typeof(DateTimeOffset),
("string", "uuid", false) => typeof(Guid),
("string", "duration", false) => typeof(TimeSpan),
("string", "char", false) => typeof(char),
("string", null, false) => typeof(string),
("object", null, false) => typeof(object),
("string", "uri", false) => typeof(Uri),
("integer", "int32", true) => typeof(int?),
("integer", "int64", true) => typeof(long?),
("number", "float", true) => typeof(float?),
("number", "double", true) => typeof(double?),
("number", "decimal", true) => typeof(decimal?),
("string", "byte", true) => typeof(byte?),
("string", "date-time", true) => typeof(DateTimeOffset?),
("string", "uuid", true) => typeof(Guid?),
("string", "char", true) => typeof(char?),
("boolean", null, true) => typeof(bool?),
_ => typeof(string),
};

return type;
}
}
}
55 changes: 55 additions & 0 deletions test/Microsoft.OpenApi.Tests/Extensions/OpenApiTypeMapperTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

using System;
using System.Collections.Generic;
using FluentAssertions;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Models;
using Xunit;

namespace Microsoft.OpenApi.Tests.Extensions
{
public class OpenApiTypeMapperTests
{
public static IEnumerable<object[]> PrimitiveTypeData => new List<object[]>
{
new object[] { typeof(int), new OpenApiSchema { Type = "integer", Format = "int32" } },
new object[] { typeof(string), new OpenApiSchema { Type = "string" } },
new object[] { typeof(double), new OpenApiSchema { Type = "number", Format = "double" } },
new object[] { typeof(float?), new OpenApiSchema { Type = "number", Format = "float", Nullable = true } },
new object[] { typeof(DateTimeOffset), new OpenApiSchema { Type = "string", Format = "date-time" } }
};

public static IEnumerable<object[]> OpenApiDataTypes => new List<object[]>
{
new object[] { new OpenApiSchema { Type = "integer", Format = "int32"}, typeof(int) },
new object[] { new OpenApiSchema { Type = "string" }, typeof(string) },
new object[] { new OpenApiSchema { Type = "number", Format = "double" }, typeof(double) },
new object[] { new OpenApiSchema { Type = "number", Format = "float", Nullable = true }, typeof(float?) },
new object[] { new OpenApiSchema { Type = "string", Format = "date-time" }, typeof(DateTimeOffset) }
};

[Theory]
[MemberData(nameof(PrimitiveTypeData))]
public void MapTypeToOpenApiPrimitiveTypeShouldSucceed(Type type, OpenApiSchema expected)
{
// Arrange & Act
var actual = OpenApiTypeMapper.MapTypeToOpenApiPrimitiveType(type);

// Assert
actual.Should().BeEquivalentTo(expected);
}

[Theory]
[MemberData(nameof(OpenApiDataTypes))]
public void MapOpenApiSchemaTypeToSimpleTypeShouldSucceed(OpenApiSchema schema, Type expected)
{
// Arrange & Act
var actual = OpenApiTypeMapper.MapOpenApiPrimitiveTypeToSimpleType(schema);

// Assert
actual.Should().Be(expected);
}
}
}
5 changes: 5 additions & 0 deletions test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,11 @@ namespace Microsoft.OpenApi.Extensions
public static void SerializeAsYaml<T>(this T element, System.IO.Stream stream, Microsoft.OpenApi.OpenApiSpecVersion specVersion)
where T : Microsoft.OpenApi.Interfaces.IOpenApiSerializable { }
}
public static class OpenApiTypeMapper
{
public static System.Type MapOpenApiPrimitiveTypeToSimpleType(this Microsoft.OpenApi.Models.OpenApiSchema schema) { }
public static Microsoft.OpenApi.Models.OpenApiSchema MapTypeToOpenApiPrimitiveType(this System.Type type) { }
}
public static class StringExtensions
{
public static T GetEnumFromDisplayName<T>(this string displayName) { }
Expand Down