Skip to content

Commit

Permalink
Fix serialization of OpType (#8105)
Browse files Browse the repository at this point in the history
  • Loading branch information
flobernd authored and github-actions[bot] committed Apr 9, 2024
1 parent ef3ecb3 commit 5f4be58
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/Elastic.Clients.Elasticsearch.Shared/Types/OpType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

using Elastic.Transport;

#if ELASTICSEARCH_SERVERLESS
Expand All @@ -10,6 +14,7 @@ namespace Elastic.Clients.Elasticsearch.Serverless;
namespace Elastic.Clients.Elasticsearch;
#endif

[JsonConverter(typeof(OpTypeConverter))]
public partial struct OpType : IStringable
{
public static OpType Index = new("index");
Expand All @@ -23,3 +28,26 @@ public partial struct OpType : IStringable

public string GetString() => Value ?? string.Empty;
}

internal sealed class OpTypeConverter :
JsonConverter<OpType>
{
public override OpType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.String)
{
throw new JsonException("Unexpected token.");
}

var value = reader.GetString();

return value switch
{
"index" => OpType.Index,
"create" => OpType.Create,
_ => throw new JsonException($"Unsupported value '{value}' for '{nameof(OpType)}' enum.")
};
}

public override void Write(Utf8JsonWriter writer, OpType value, JsonSerializerOptions options) => writer.WriteStringValue(value.Value);
}

0 comments on commit 5f4be58

Please sign in to comment.