| | | 1 | | using System.Text.Json; |
| | | 2 | | using Elsa.Expressions.Models; |
| | | 3 | | using Elsa.Extensions; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Workflows.UIHints.Dictionary; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// A class that evaluates activity inputs configured to be dictionaries. It resolves expressions and modifies the input |
| | | 10 | | /// </summary> |
| | 0 | 11 | | public class DictionaryValueEvaluator(ILogger<DictionaryValueEvaluator> logger) : IActivityInputEvaluator |
| | | 12 | | { |
| | | 13 | | public async Task<object?> EvaluateAsync(ActivityInputEvaluatorContext context) |
| | | 14 | | { |
| | 0 | 15 | | var wrappedInput = context.Input; |
| | 0 | 16 | | var evaluator = context.ExpressionEvaluator; |
| | 0 | 17 | | var expressionExecutionContext = context.ExpressionExecutionContext; |
| | 0 | 18 | | var inputDescriptor = context.InputDescriptor; |
| | 0 | 19 | | var defaultValue = inputDescriptor.DefaultValue; |
| | 0 | 20 | | var value = wrappedInput.Expression != null ? await evaluator.EvaluateAsync(wrappedInput, expressionExecutionCon |
| | | 21 | | |
| | 0 | 22 | | if (value is not IDictionary<string, object> dictionary || inputDescriptor.UIHint != InputUIHints.Dictionary) |
| | 0 | 23 | | return value; |
| | | 24 | | |
| | 0 | 25 | | var tempDictionary = new Dictionary<string, object?>(dictionary.Count); |
| | 0 | 26 | | foreach (var dict in dictionary) |
| | | 27 | | { |
| | 0 | 28 | | if (dict.Value is not JsonElement json) |
| | | 29 | | { |
| | | 30 | | // Not a JSON object, so just use the value as-is. |
| | 0 | 31 | | tempDictionary[dict.Key] = dict.Value; |
| | 0 | 32 | | continue; |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | // JSON object, so extract the type and value properties. |
| | 0 | 36 | | var hasType = json.TryGetProperty("type", out var typeProperty); |
| | 0 | 37 | | var hasValue = json.TryGetProperty("value", out var valueProperty); |
| | | 38 | | |
| | 0 | 39 | | if (!hasType || !hasValue) |
| | | 40 | | { |
| | | 41 | | // Skip this entry or handle as needed (e.g., log, throw, etc.) |
| | 0 | 42 | | logger.LogWarning("Dictionary entry is missing type or value property: {Json}", JsonSerializer.Serialize |
| | 0 | 43 | | continue; |
| | | 44 | | } |
| | | 45 | | |
| | | 46 | | // Evaluate the expression. |
| | 0 | 47 | | var expression = new Expression(typeProperty.ToString(), valueProperty.ToString()); |
| | 0 | 48 | | var val = await evaluator.EvaluateAsync<object>(expression, expressionExecutionContext); |
| | | 49 | | |
| | | 50 | | // Add the evaluated value to the dictionary. |
| | 0 | 51 | | tempDictionary[dict.Key] = val; |
| | 0 | 52 | | } |
| | | 53 | | |
| | | 54 | | // Replace the original dictionary with the evaluated one. |
| | 0 | 55 | | value = tempDictionary; |
| | | 56 | | |
| | 0 | 57 | | return value; |
| | 0 | 58 | | } |
| | | 59 | | } |