| | | 1 | | using System.Text.Json; |
| | | 2 | | using Elsa.Api.Client.Shared.Models; |
| | | 3 | | |
| | | 4 | | namespace Elsa.Api.Client.Extensions; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Provides extension methods for the PropertyBag class. |
| | | 8 | | /// </summary> |
| | | 9 | | public static class PropertyBagExtensions |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Tries to retrieve a value from the PropertyBag based on the provided key. |
| | | 13 | | /// If the specified key does not exist in the PropertyBag, the method will return the default value obtained from t |
| | | 14 | | /// </summary> |
| | | 15 | | /// <typeparam name="T">The type of the value to retrieve.</typeparam> |
| | | 16 | | /// <param name="propertyBag">The PropertyBag to retrieve the value from.</param> |
| | | 17 | | /// <param name="key">The key of the value to retrieve.</param> |
| | | 18 | | /// <param name="defaultValue">A function that returns the default value to be returned if the key does not exist in |
| | | 19 | | /// <returns>The value associated with the key, or the default value if the key does not exist.</returns> |
| | | 20 | | public static T? TryGetValueOrDefault<T>(this PropertyBag propertyBag, string key, Func<T> defaultValue) |
| | | 21 | | { |
| | 0 | 22 | | if (!propertyBag.TryGetValue(key, out var value)) |
| | 0 | 23 | | return defaultValue(); |
| | | 24 | | |
| | 0 | 25 | | var json = value.ToString(); |
| | | 26 | | |
| | 0 | 27 | | if (string.IsNullOrWhiteSpace(json)) |
| | 0 | 28 | | return defaultValue(); |
| | | 29 | | |
| | 0 | 30 | | return JsonSerializer.Deserialize<T>(json); |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | /// <summary> |
| | | 34 | | /// Sets a value in the PropertyBag based on the provided key. |
| | | 35 | | /// The value is serialized using JSON. |
| | | 36 | | /// </summary> |
| | | 37 | | /// <param name="propertyBag">The PropertyBag to set the value in.</param> |
| | | 38 | | /// <param name="key">The key to associate with the value.</param> |
| | | 39 | | /// <param name="value">The value to store in the PropertyBag.</param> |
| | | 40 | | public static void SetValue(this PropertyBag propertyBag, string key, object value) |
| | | 41 | | { |
| | 0 | 42 | | var json = JsonSerializer.Serialize(value); |
| | 0 | 43 | | propertyBag[key] = json; |
| | 0 | 44 | | } |
| | | 45 | | } |