| | | 1 | | using System.Text.Json; |
| | | 2 | | |
| | | 3 | | namespace Kestrun.Callback; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// JSON implementation of <see cref="ICallbackBodySerializer"/>. |
| | | 7 | | /// </summary> |
| | | 8 | | public sealed class JsonCallbackBodySerializer : ICallbackBodySerializer |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Serializes the callback body based on the provided plan and context. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <param name="plan">The callback plan containing the body definition.</param> |
| | | 14 | | /// <param name="ctx">The callback runtime context providing the payload.</param> |
| | | 15 | | /// <returns>A tuple containing the content type and serialized body bytes.</returns> |
| | | 16 | | public (string ContentType, byte[] Body) Serialize(CallbackPlan plan, CallbackRuntimeContext ctx) |
| | | 17 | | { |
| | | 18 | | // If no body defined in plan → send empty |
| | 3 | 19 | | if (plan.Body is null) |
| | | 20 | | { |
| | 1 | 21 | | return ("application/json", Array.Empty<byte>()); |
| | | 22 | | } |
| | | 23 | | |
| | 2 | 24 | | var ct = plan.Body.MediaType ?? "application/json"; |
| | | 25 | | |
| | | 26 | | // Your payload must be provided by handler earlier |
| | 2 | 27 | | if (ctx.CallbackPayload is null) |
| | | 28 | | { |
| | 1 | 29 | | return (ct, Array.Empty<byte>()); |
| | | 30 | | } |
| | | 31 | | |
| | 1 | 32 | | var bytes = JsonSerializer.SerializeToUtf8Bytes(ctx.CallbackPayload); |
| | 1 | 33 | | return (ct, bytes); |
| | | 34 | | } |
| | | 35 | | } |