diff --git a/src/Configuration.cs b/src/Configuration.cs index 3841ef7..80018b2 100644 --- a/src/Configuration.cs +++ b/src/Configuration.cs @@ -47,6 +47,17 @@ public IConfigurationNode this[string key] // │ Public Methods │ // └─────────────────────────────────────────────────────────────────────────────┘ + /// + public T Get() + { + if (configurationNode is null) + { + return default!; + } + + return configurationNode.Get(); + } + /// public bool TryGet(string key, out T? value) { diff --git a/src/ConfigurationNode.cs b/src/ConfigurationNode.cs index a478f52..85cb6b0 100644 --- a/src/ConfigurationNode.cs +++ b/src/ConfigurationNode.cs @@ -1,5 +1,6 @@ namespace WB.Configuration; +using System; using System.Text.Json; using System.Text.Json.Nodes; @@ -15,6 +16,19 @@ internal sealed class ConfigurationNode(JsonNode? jsonNode) : IConfigurationNode // │ Public Indexers │ // └─────────────────────────────────────────────────────────────────────────────┘ + /// + public T Get() + { + if (jsonNode is null) + { + return default!; + } + + T? result = jsonNode.Deserialize() ?? throw new InvalidOperationException($"Failed to deserialize JSON node to type {typeof(T).FullName}."); + + return result; + } + /// public IConfigurationNode this[string key] { diff --git a/src/IConfigurationNode.cs b/src/IConfigurationNode.cs index 5533187..bff9340 100644 --- a/src/IConfigurationNode.cs +++ b/src/IConfigurationNode.cs @@ -30,6 +30,8 @@ public interface IConfigurationNode // │ Public Methods │ // └─────────────────────────────────────────────────────────────────────────────┘ + public T Get(); + /// /// Tries to get a value of type associated with the specified key. Returns true if the key exists and the value can be converted to type ; otherwise, returns false and sets the output parameter to default. /// diff --git a/tests/ConfigurationNodeTests/src/MethodTests/GetMethodTests.cs b/tests/ConfigurationNodeTests/src/MethodTests/GetMethodTests.cs new file mode 100644 index 0000000..980a5c2 --- /dev/null +++ b/tests/ConfigurationNodeTests/src/MethodTests/GetMethodTests.cs @@ -0,0 +1,33 @@ +using System.Text.Json.Nodes; +using AwesomeAssertions; + +namespace WB.Configuration; + +public sealed class GetMethodTests +{ + [Test] + public void ShouldReturnDefaultValue_WhenCurrentNodeIsNull() + { + // Arrange + ConfigurationNode configurationNode = new(null); + + // Act + string? value = configurationNode.Get(); + + // Assert + value.Should().BeNull(because: "the current node is null and should return the default value for the requested type"); + } + + [Test] + public void ShouldReturnDeserializedValue_WhenCurrentNodeIsValidJson() + { + // Arrange + ConfigurationNode configurationNode = new(JsonNode.Parse("\"value\"")); + + // Act + string? value = configurationNode.Get(); + + // Assert + value.Should().Be("value", because: "the current node contains valid JSON that can be deserialized to the requested type"); + } +}