Skip to content

Commit

Permalink
Add conversion helpers for E5EEvent
Browse files Browse the repository at this point in the history
  • Loading branch information
nachtjasmin committed Oct 26, 2023
1 parent 71cef60 commit 43fdc34
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/Anexia.E5E/Exceptions/E5EInvalidConversionException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Anexia.E5E.Functions;

namespace Anexia.E5E.Exceptions;

/// <summary>
/// Thrown when a <see cref="E5EEvent" /> is converted into the wrong format.
/// </summary>
public class E5EInvalidConversionException :E5EException
{
/// <summary>
/// The required data type for this conversion call.
/// </summary>
public E5ERequestDataType Expected { get; }

/// <summary>
/// The actual data type.
/// </summary>
public E5ERequestDataType Actual { get; }

internal E5EInvalidConversionException(E5ERequestDataType expected, E5ERequestDataType actual)
: base($"Cannot convert data of type {actual} into the type {expected}")
{
Expected = expected;
Actual = actual;
}

internal static void ThrowIfNotMatch(E5ERequestDataType expected, E5ERequestDataType actual)
{
if (expected != actual)
throw new E5EInvalidConversionException(expected, actual);
}
}
23 changes: 23 additions & 0 deletions src/Anexia.E5E/Functions/E5EEvent.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using System.ComponentModel;
using System.Text.Json;

using Anexia.E5E.Exceptions;

namespace Anexia.E5E.Functions;

/// <summary>
Expand All @@ -22,4 +25,24 @@ public record E5EEvent(E5ERequestDataType Type,
/// <returns>A <typeparamref name="TValue"/> representation of the JSON.</returns>
/// <exception cref="JsonException">If <typeparamref name="TValue"/> is not compatible with the JSON.</exception>
public TValue? As<TValue>(JsonSerializerOptions? options = null) => Data.Deserialize<TValue>(options);

/// <summary>
/// Returns the value as string.
/// </summary>
/// <exception cref="E5EInvalidConversionException">Thrown if <see cref="Type"/> is not <see cref="E5ERequestDataType.Text"/>.</exception>
public string? AsText()
{
E5EInvalidConversionException.ThrowIfNotMatch(E5ERequestDataType.Text, Type);
return As<string>();
}

/// <summary>
/// Returns the value as string.
/// </summary>
/// <exception cref="E5EInvalidConversionException">Thrown if <see cref="Type"/> is not <see cref="E5ERequestDataType.Binary"/>.</exception>
public byte[]? AsByteArray()
{
E5EInvalidConversionException.ThrowIfNotMatch(E5ERequestDataType.Binary, Type);
return As<byte[]>();
}
}

0 comments on commit 43fdc34

Please sign in to comment.