Skip to content

Commit

Permalink
Added generic NamedType helper. (#7923)
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelstaib committed Jan 9, 2025
1 parent 239719c commit a0207c0
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/HotChocolate/Core/src/Types/Types/Extensions/TypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,54 @@ public static ListType ListType(this IType type)
throw new ArgumentException(TypeResources.TypeExtensions_InvalidStructure);
}

/// <summary>
/// Gets the named type (the most inner type) from a type structure.
/// </summary>
/// <param name="type">
/// The type from which the named type shall be extracted.
/// </param>
/// <typeparam name="T">
/// The expected type of the named type.
/// </typeparam>
/// <returns>
/// Returns the named type.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The type structure is invalid or
/// the named type is not of the expected type.
/// </exception>
public static T NamedType<T>(this IType type) where T : INamedType
{
var namedType = type.NamedType();

if(namedType is T t)
{
return t;
}

throw new ArgumentException(
"The named type is not of the expected type.",
nameof(type));
}

/// <summary>
/// Gets the named type (the most inner type) from a type structure.
/// </summary>
/// <param name="type">
/// The type from which the named type shall be extracted.
/// </param>
/// <returns>
/// Returns the named type.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The type structure is invalid.
/// </exception>
public static INamedType NamedType(this IType type)
{
if (type is null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,35 @@ public static void NamedType()
Assert.NotNull(stringType);
}

[Fact]
public static void NamedType_Of_T()
{
// arrange
var type = new NonNullType(
new ListType(
new NonNullType(
new StringType())));

// act
var stringType = type.NamedType<StringType>();

// assert
Assert.NotNull(stringType);
}

[Fact]
public static void NamedType_Of_T_Is_Not_Of_T()
{
// arrange
var type = new NonNullType(
new ListType(
new NonNullType(
new StringType())));

// act & assert
Assert.Throws<ArgumentException>(() => type.NamedType<ObjectType>());
}

[Fact]
public static void NamedType_Type_Is_Null()
{
Expand Down

0 comments on commit a0207c0

Please sign in to comment.