| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using System.Text.Json.Serialization; |
| | | 4 | | using CShells.FastEndpoints.Contracts; |
| | | 5 | | using Elsa.Workflows; |
| | | 6 | | using FastEndpoints; |
| | | 7 | | using JetBrains.Annotations; |
| | | 8 | | using Microsoft.AspNetCore.Http; |
| | | 9 | | using Microsoft.Extensions.DependencyInjection; |
| | | 10 | | |
| | | 11 | | namespace Elsa.FastEndpointConfigurators; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Configures FastEndpoints with Elsa-specific serialization options. |
| | | 15 | | /// Uses the same serialization settings as <see cref="Elsa.Extensions.WebApplicationExtensions.UseWorkflowsApi"/>. |
| | | 16 | | /// </summary> |
| | | 17 | | [UsedImplicitly] |
| | | 18 | | public class ElsaFastEndpointsConfigurator : IFastEndpointsConfigurator |
| | | 19 | | { |
| | | 20 | | /// <inheritdoc /> |
| | | 21 | | public void Configure(Config config) |
| | | 22 | | { |
| | 0 | 23 | | config.Serializer.RequestDeserializer = DeserializeRequestAsync; |
| | 0 | 24 | | config.Serializer.ResponseSerializer = SerializeResponseAsync; |
| | | 25 | | |
| | 0 | 26 | | config.Binding.ValueParserFor<DateTimeOffset>(s => |
| | 0 | 27 | | new(DateTimeOffset.TryParse(s.ToString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out va |
| | 0 | 28 | | } |
| | | 29 | | |
| | | 30 | | private static ValueTask<object?> DeserializeRequestAsync(HttpRequest httpRequest, Type modelType, JsonSerializerCon |
| | | 31 | | { |
| | 0 | 32 | | var serializer = httpRequest.HttpContext.RequestServices.GetRequiredService<IApiSerializer>(); |
| | 0 | 33 | | var options = serializer.GetOptions(); |
| | | 34 | | |
| | 0 | 35 | | return serializerContext == null |
| | 0 | 36 | | ? JsonSerializer.DeserializeAsync(httpRequest.Body, modelType, options, cancellationToken) |
| | 0 | 37 | | : JsonSerializer.DeserializeAsync(httpRequest.Body, modelType, serializerContext, cancellationToken); |
| | | 38 | | } |
| | | 39 | | |
| | | 40 | | private static Task SerializeResponseAsync(HttpResponse httpResponse, object? dto, string contentType, JsonSerialize |
| | | 41 | | { |
| | 0 | 42 | | var serializer = httpResponse.HttpContext.RequestServices.GetRequiredService<IApiSerializer>(); |
| | 0 | 43 | | var options = serializer.GetOptions(); |
| | | 44 | | |
| | 0 | 45 | | httpResponse.ContentType = contentType; |
| | 0 | 46 | | return serializerContext == null |
| | 0 | 47 | | ? JsonSerializer.SerializeAsync(httpResponse.Body, dto, dto?.GetType() ?? typeof(object), options, cancellat |
| | 0 | 48 | | : JsonSerializer.SerializeAsync(httpResponse.Body, dto, dto?.GetType() ?? typeof(object), serializerContext, |
| | | 49 | | } |
| | | 50 | | } |