w4c-workflows-api/Services/Nodes/NodeParameterReader.cs
2026-09-12 01:02:46 +03:00

69 lines
2.5 KiB
C#

using System.Collections;
using System.Globalization;
using System.Text.Json.Nodes;
namespace w4c_workflows.Services.Nodes;
/// <summary>
/// Converts the loosely-typed values YamlDotNet produces (scalars, nested
/// <c>Dictionary&lt;object, object&gt;</c> mappings and <c>List&lt;object&gt;</c>
/// sequences) into <see cref="JsonNode"/>, so node parameters keep their YAML
/// types and can be interpolated by the shared engine.
/// </summary>
public static class NodeParameterReader
{
/// <summary>Builds a JSON object from a YAML mapping (null-safe).</summary>
public static JsonObject ToJsonObject(Dictionary<string, object?>? mapping)
{
var result = new JsonObject();
if (mapping == null)
return result;
foreach (var (key, value) in mapping)
result[key] = ToJsonNode(value);
return result;
}
/// <summary>Converts a single YamlDotNet value into a JSON node.</summary>
public static JsonNode? ToJsonNode(object? value) => value switch
{
null => null,
JsonNode node => node.DeepClone(),
string text => JsonValue.Create(text),
bool flag => JsonValue.Create(flag),
char ch => JsonValue.Create(ch.ToString()),
sbyte or byte or short or ushort or int or uint or long
=> JsonValue.Create(Convert.ToInt64(value, CultureInfo.InvariantCulture)),
ulong unsigned => JsonValue.Create(unsigned),
float or double or decimal
=> JsonValue.Create(Convert.ToDecimal(value, CultureInfo.InvariantCulture)),
DateTime dateTime => JsonValue.Create(dateTime.ToString("O", CultureInfo.InvariantCulture)),
DateTimeOffset offset => JsonValue.Create(offset.ToString("O", CultureInfo.InvariantCulture)),
IDictionary dictionary => FromDictionary(dictionary),
IEnumerable sequence => FromSequence(sequence),
_ => JsonValue.Create(value.ToString()),
};
private static JsonObject FromDictionary(IDictionary dictionary)
{
var result = new JsonObject();
foreach (DictionaryEntry entry in dictionary)
{
var key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture);
if (string.IsNullOrEmpty(key))
continue;
result[key] = ToJsonNode(entry.Value);
}
return result;
}
private static JsonArray FromSequence(IEnumerable sequence)
{
var result = new JsonArray();
foreach (var element in sequence)
result.Add(ToJsonNode(element));
return result;
}
}