Skip to content

Commit

Permalink
feat: Added ability to pass JsonSerializerOptions.
Browse files Browse the repository at this point in the history
  • Loading branch information
HavenDV committed Jun 5, 2024
1 parent 711136f commit e105a70
Show file tree
Hide file tree
Showing 643 changed files with 2,323 additions and 923 deletions.
24 changes: 21 additions & 3 deletions src/libs/OpenApiGenerator.Core/Generation/Data.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ public static (EquatableArray<ModelData> Models, EquatableArray<EndPoint> Method
!settings.ExcludeTags.Contains(x.Name))
.ToArray();
EndPoint[] constructors = settings.GenerateSdk || settings.GenerateConstructors ? [new EndPoint(
Id: "Constructors",
Id: "MainConstructor",
Namespace: settings.Namespace,
ClassName: settings.ClassName.Replace(".", string.Empty),
BaseUrl: openApiDocument.Servers.FirstOrDefault()?.Url ?? string.Empty,
Expand Down Expand Up @@ -155,7 +155,8 @@ .. includedTags.Select(x => PropertyData.Default with
RequestType: TypeData.Default,
ResponseType: TypeData.Default,
AdditionalModels: [],
AdditionalTypes: [])] : [];
AdditionalTypes: [],
Converters: [])] : [];
if (settings.GroupByTags && (settings.GenerateSdk || settings.GenerateConstructors))
{
constructors = constructors.Concat(
Expand All @@ -177,7 +178,8 @@ .. includedTags.Select(x => PropertyData.Default with
RequestType: TypeData.Default,
ResponseType: TypeData.Default,
AdditionalModels: [],
AdditionalTypes: [])))
AdditionalTypes: [],
Converters: [])))
.ToArray();
}

Expand Down Expand Up @@ -250,6 +252,22 @@ .. includedTags.Select(x => PropertyData.Default with
.GroupBy(x => x.FileNameWithoutExtension)
.Select(x => x.First())
.ToImmutableArray() : [];

for (var i = 0; i < methods.Length; i++)
{
if (methods[i].Id != "MainConstructor")
{
continue;
}

methods[i] = methods[i] with
{
Converters = models
.Where(x => x.Style == ModelStyle.Enumeration && x.JsonSerializerType != JsonSerializerType.NewtonsoftJson)
.Select(x => $"global::OpenApiGenerator.JsonConverters.{x.ClassName}JsonConverter")
.ToImmutableArray(),
};
}

return (Models: models,
Methods: settings.GenerateSdk || settings.GenerateMethods
Expand Down
15 changes: 13 additions & 2 deletions src/libs/OpenApiGenerator.Core/Generation/Sources.Clients.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using OpenApiGenerator.Core.Extensions;
using OpenApiGenerator.Core.Json;
using OpenApiGenerator.Core.Models;

namespace OpenApiGenerator.Core.Generation;
Expand All @@ -8,6 +9,9 @@ public static partial class Sources
public static string GenerateConstructors(
EndPoint endPoint)
{
var serializer = endPoint.JsonSerializerType.GetSerializer();
var hasOptions = string.IsNullOrWhiteSpace(endPoint.JsonSerializerContext);

return $@"
#nullable enable
Expand All @@ -17,9 +21,12 @@ namespace {endPoint.Namespace}
public sealed partial class {endPoint.ClassName} : global::System.IDisposable
{{
private readonly global::System.Net.Http.HttpClient _httpClient;
{(hasOptions ? $@"
private readonly {serializer.GetOptionsType()} _jsonSerializerOptions;" : " ")}
{(endPoint.Properties.Length != 0 ? "\n" + endPoint.Properties.Select(x => $@"
{x.Summary.ToXmlDocumentationSummary(level: 8)}
public {x.Type.CSharpType} {x.Name} => new {x.Type.CSharpType}(_httpClient);
public {x.Type.CSharpType} {x.Name} => new {x.Type.CSharpType}(_httpClient{(hasOptions ? ", jsonSerializerOptions: _jsonSerializerOptions" : "")});
").Inject() : " ")}
/// <summary>
Expand All @@ -31,10 +38,14 @@ public sealed partial class {endPoint.ClassName} : global::System.IDisposable
/// <param name=""baseUri""></param>
public {endPoint.ClassName}(
global::System.Net.Http.HttpClient? httpClient = null,
global::System.Uri? baseUri = null)
global::System.Uri? baseUri = null{(hasOptions ? $@",
{serializer.GetOptionsType()}? jsonSerializerOptions = null" : " ")}
)
{{
_httpClient = httpClient ?? new global::System.Net.Http.HttpClient();
_httpClient.BaseAddress ??= baseUri ?? new global::System.Uri(""{endPoint.BaseUrl}"");
{(hasOptions ? $@"
_jsonSerializerOptions = _jsonSerializerOptions ?? {(endPoint.Id == "MainConstructor" ? serializer.CreateDefaultSettings(endPoint.Converters) : $"new {serializer.GetOptionsType()}()")};" : " ")}
}}
/// <inheritdoc/>
Expand Down
2 changes: 2 additions & 0 deletions src/libs/OpenApiGenerator.Core/Json/IJsonSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ public interface IJsonSerializer
string GenerateDeserializeCall(string type, string jsonSerializerContext);
string GenerateSerializeCall(string type, string jsonSerializerContext);
string GenerateConverterAttribute(string type);
string GetOptionsType();
string CreateDefaultSettings(IReadOnlyList<string> converters);
}
16 changes: 14 additions & 2 deletions src/libs/OpenApiGenerator.Core/Json/NewtonsoftJsonSerializer.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using OpenApiGenerator.Core.Extensions;

namespace OpenApiGenerator.Core.Json;

public class NewtonsoftJsonSerializer : IJsonSerializer
Expand All @@ -19,6 +21,16 @@ public string GenerateRequiredAttribute()
{
return string.Empty;
}

public string GetOptionsType()
{
return "global::Newtonsoft.Json.JsonSerializerSettings";
}

public string CreateDefaultSettings(IReadOnlyList<string> converters)
{
return "new global::Newtonsoft.Json.JsonSerializerSettings()";
}

public string GenerateConverterAttribute(string type)
{
Expand All @@ -27,11 +39,11 @@ public string GenerateConverterAttribute(string type)

public string GenerateSerializeCall(string type, string jsonSerializerContext)
{
return "global::Newtonsoft.Json.JsonConvert.SerializeObject(request)";
return "global::Newtonsoft.Json.JsonConvert.SerializeObject(request, _jsonSerializerOptions)";
}

public string GenerateDeserializeCall(string type, string jsonSerializerContext)
{
return $"global::Newtonsoft.Json.JsonConvert.DeserializeObject<{type}>(__content)";
return $"global::Newtonsoft.Json.JsonConvert.DeserializeObject<{type}>(__content, _jsonSerializerOptions)";
}
}
26 changes: 24 additions & 2 deletions src/libs/OpenApiGenerator.Core/Json/SystemTextJsonSerializer.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using OpenApiGenerator.Core.Extensions;

namespace OpenApiGenerator.Core.Json;

public class SystemTextJsonSerializer : IJsonSerializer
Expand All @@ -18,6 +20,26 @@ public string GenerateRequiredAttribute()
{
return "[global::System.Text.Json.Serialization.JsonRequired]";
}

public string GetOptionsType()
{
return "global::System.Text.Json.JsonSerializerOptions";
}

public string CreateDefaultSettings(IReadOnlyList<string> converters)
{
return @$"new global::System.Text.Json.JsonSerializerOptions
{{
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = global::System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
Converters =
{{
{converters.Select(x => $@"
new {x}(),
").Inject()}
}}
}}";
}

public string GenerateConverterAttribute(string type)
{
Expand Down Expand Up @@ -68,7 +90,7 @@ public string GenerateSerializeCall(string type, string jsonSerializerContext)
type = type ?? throw new ArgumentNullException(nameof(type));

return string.IsNullOrWhiteSpace(jsonSerializerContext)
? "global::System.Text.Json.JsonSerializer.Serialize(request)"
? "global::System.Text.Json.JsonSerializer.Serialize(request, _jsonSerializerOptions)"
: $"global::System.Text.Json.JsonSerializer.Serialize(request, global::{jsonSerializerContext}.Default.{GetContextType(type)})";
}

Expand All @@ -77,7 +99,7 @@ public string GenerateDeserializeCall(string type, string jsonSerializerContext)
type = type ?? throw new ArgumentNullException(nameof(type));

return string.IsNullOrWhiteSpace(jsonSerializerContext)
? $"global::System.Text.Json.JsonSerializer.Deserialize<{type}>(__content)"
? $"global::System.Text.Json.JsonSerializer.Deserialize<{type}>(__content, _jsonSerializerOptions)"
: $"global::System.Text.Json.JsonSerializer.Deserialize(__content, global::{jsonSerializerContext}.Default.{GetContextType(type)})";
}
}
9 changes: 6 additions & 3 deletions src/libs/OpenApiGenerator.Core/Models/EndPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ public readonly record struct EndPoint(
TypeData RequestType,
TypeData ResponseType,
ImmutableArray<ModelData> AdditionalModels,
ImmutableArray<TypeData> AdditionalTypes
ImmutableArray<TypeData> AdditionalTypes,
ImmutableArray<string> Converters
)
{
public string MethodName => $"{NotAsyncMethodName}Async";
Expand Down Expand Up @@ -202,7 +203,8 @@ public static EndPoint FromSchema(
AdditionalTypes: [
..requestBodyTypes,
..responseTypes,
]);
],
Converters: []);

return endPoint;
}
Expand All @@ -228,7 +230,8 @@ public static EndPoint FromAuthorization(
RequestType: TypeData.Default,
ResponseType: TypeData.Default,
AdditionalModels: [],
AdditionalTypes: []);
AdditionalTypes: [],
Converters: []);

return endPoint;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ namespace G
public sealed partial class Api : global::System.IDisposable
{
private readonly global::System.Net.Http.HttpClient _httpClient;
private readonly global::Newtonsoft.Json.JsonSerializerSettings _jsonSerializerOptions;


/// <summary>
/// Move projects to or from GitHub.
/// </summary>
public MigrationsClient Migrations => new MigrationsClient(_httpClient);
public MigrationsClient Migrations => new MigrationsClient(_httpClient, jsonSerializerOptions: _jsonSerializerOptions);

/// <summary>
/// Creates a new instance of the Api.
Expand All @@ -27,10 +29,13 @@ public sealed partial class Api : global::System.IDisposable
/// <param name="baseUri"></param>
public Api(
global::System.Net.Http.HttpClient? httpClient = null,
global::System.Uri? baseUri = null)
global::System.Uri? baseUri = null,
global::Newtonsoft.Json.JsonSerializerSettings? jsonSerializerOptions = null
)
{
_httpClient = httpClient ?? new global::System.Net.Http.HttpClient();
_httpClient.BaseAddress ??= baseUri ?? new global::System.Uri("https://api.github.com");
_jsonSerializerOptions = _jsonSerializerOptions ?? new global::Newtonsoft.Json.JsonSerializerSettings();
}

/// <inheritdoc/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<BasicError?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<BasicError?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<BasicError?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<BasicError?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<BasicError?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<BasicError?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<BasicError?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<BasicError?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<BasicError?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<BasicError?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<global::System.Collections.Generic.IList<PorterAuthor>?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<global::System.Collections.Generic.IList<PorterAuthor>?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<Import?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<Import?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<global::System.Collections.Generic.IList<PorterLargeFile>?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<global::System.Collections.Generic.IList<PorterLargeFile>?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<Migration?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<Migration?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<Migration?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<Migration?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<global::System.Collections.Generic.IList<Migration>?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<global::System.Collections.Generic.IList<Migration>?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<global::System.Collections.Generic.IList<Migration>?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<global::System.Collections.Generic.IList<Migration>?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<global::System.Collections.Generic.IList<MinimalRepository>?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<global::System.Collections.Generic.IList<MinimalRepository>?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<global::System.Collections.Generic.IList<MinimalRepository>?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<global::System.Collections.Generic.IList<MinimalRepository>?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public partial class MigrationsClient
method: global::System.Net.Http.HttpMethod.Patch,
requestUri: new global::System.Uri(_httpClient.BaseAddress?.AbsoluteUri + $"/repos/{owner}/{repo}/import/authors/{authorId}", global::System.UriKind.RelativeOrAbsolute));
httpRequest.Content = new global::System.Net.Http.StringContent(
content: global::Newtonsoft.Json.JsonConvert.SerializeObject(request),
content: global::Newtonsoft.Json.JsonConvert.SerializeObject(request, _jsonSerializerOptions),
encoding: global::System.Text.Encoding.UTF8,
mediaType: "application/json");

Expand All @@ -41,7 +41,7 @@ public partial class MigrationsClient
var __content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

return
global::Newtonsoft.Json.JsonConvert.DeserializeObject<PorterAuthor?>(__content) ??
global::Newtonsoft.Json.JsonConvert.DeserializeObject<PorterAuthor?>(__content, _jsonSerializerOptions) ??
throw new global::System.InvalidOperationException($"Response deserialization failed for \"{__content}\" ");
}

Expand Down
Loading

0 comments on commit e105a70

Please sign in to comment.