Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for array and nullable parameters in Action.Url #124

Merged
merged 2 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@ WithRouteAttribute:sd
SomeComplexTest:Url/akacja/${par1}/${par2}/${par3}?par4=${par4}&par5=${par5}
WithEnumParam:Url?numbers=${numbers}
WithOptionalParam:Url?optional=${optional}
WithOptionalObjectParam:Url/object-param?date=${optional?.date}&temperatureC=${optional?.temperatureC}&temperatureF=${optional?.temperatureF}&summary=${optional?.summary}
WithArrayParam:Url/array-param?${array.map(item => `array=${encodeURIComponent(item)}`).join('&')}
WithArrayInObjectParam:Url/array-in-object-param?${optional?.arrayStr.map(item => `arrayStr=${encodeURIComponent(item)}`).join('&')}&${optional?.listStr.map(item => `listStr=${encodeURIComponent(item)}`).join('&')}&${optional?.arrayEnum.map(item => `arrayEnum=${item}`).join('&')}&${optional?.listEnum.map(item => `listEnum=${item}`).join('&')}
WithNullableArrayInObjectParam:Url/nullable-array-in-object-param?${optional?.arrayStr?.map(item => `arrayStr=${encodeURIComponent(item)}`).join('&')}&${optional?.listStr?.map(item => `listStr=${encodeURIComponent(item)}`).join('&')}&${optional?.arrayEnum?.map(item => `arrayEnum=${item}`).join('&')}&${optional?.listEnum?.map(item => `listEnum=${item}`).join('&')}
33 changes: 30 additions & 3 deletions NTypewriter.CodeModel.Functions/ActionFunctions.Url.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,22 +123,49 @@ private static string AppendFromQuery(IMethod method, string route)
{
foreach (var prop in @class.Properties)
{
string urlParam = prop.BareName.ToLowerFirst();
string memberAccessOperator = IsNullable(parameter) ? "?." : ".";
string propertyAccess = string.Concat(parameter.BareName, memberAccessOperator, prop.BareName.ToLowerFirst());

builder.Append(connector);
if (parameter.Type.Name == "string")
if (prop.Type.IsEnumerable && !prop.Type.IsSimple())
{
builder.Append($"{prop.BareName.ToLowerFirst()}=${{encodeURIComponent({parameter.BareName}.{prop.BareName.ToLowerFirst()})}}");
string itemValue = GetEnumerableType(prop.Type)?.Name == "string" ? "${encodeURIComponent(item)}" : "${item}";
builder.Append($"${{{propertyAccess}{(prop.Type.IsNullable ? "?." : ".")}map(item => `{urlParam}={itemValue}`).join('&')}}");
}
else
{
builder.Append($"{prop.BareName.ToLowerFirst()}=${{{parameter.BareName}.{prop.BareName.ToLowerFirst()}}}");
string urlValue = parameter.Type.Name == "string" ? $"${{encodeURIComponent({propertyAccess})}}" : $"${{{propertyAccess}}}";
builder.Append($"{urlParam}={urlValue}");
}
connector = "&";
}
}
else if (parameter.Type.IsEnumerable)
{
string urlParam = parameter.BareName.ToLowerFirst();
string memberAccessOperator = IsNullable(parameter) ? "?." : ".";
string itemValue = GetEnumerableType(parameter.Type)?.Name == "string" ? "${encodeURIComponent(item)}" : "${item}";

builder.Append(connector).Append($"${{{parameter.BareName}{memberAccessOperator}map(item => `{urlParam}={itemValue}`).join('&')}}");
connector = "&";
}
}
}
var postfix = builder.ToString();
return route + postfix;
}

private static IType GetEnumerableType(IType enumerableType)
{
if (!enumerableType.IsEnumerable)
return null;
return enumerableType.ArrayType ?? enumerableType.TypeArguments.FirstOrDefault();
}

private static bool IsNullable(IParameter parameter)
{
return parameter.Type.IsNullable || (parameter.HasDefaultValue && parameter.DefaultValue == null);
}
}
}
18 changes: 13 additions & 5 deletions NTypewriter.CodeModel.Functions/Extensions/ITypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ internal static class ITypeExtensions
// https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-5.0#simple-types
public static bool IsSimple(this IType type)
{
if (type.IsNullable)
if (type.IsNullable)
{
if (type.TypeArguments.Any())
{
return IsSimple(type.TypeArguments.First());
}
var nonNullableType = GetUnderlyingNonNullableType(type);
if (nonNullableType != null)
return IsSimple(nonNullableType);
}
switch (type.FullName)
{
Expand All @@ -31,5 +30,14 @@ public static bool IsSimple(this IType type)

return type.IsPrimitive || type.IsEnum;
}

public static IType GetUnderlyingNonNullableType(this IType type)
{
if (!type.IsNullable)
return null;
if (type.IsReferenceType)
return type.OriginalDefinition;
return type.TypeArguments.FirstOrDefault();
}
}
}
1 change: 1 addition & 0 deletions NTypewriter.CodeModel.Roslyn/Type.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public bool IsPrimitive
public IEnumerable<IInterface> Interfaces => InterfaceCollection.Create(symbol.Interfaces);
public IEnumerable<IInterface> AllInterfaces => InterfaceCollection.Create(symbol.AllInterfaces);
public IType ArrayType => symbol is IArrayTypeSymbol arraySymbol ? NTypewriter.CodeModel.Roslyn.Type.Create(arraySymbol.ElementType) : null;
public IType OriginalDefinition => NTypewriter.CodeModel.Roslyn.Type.Create(symbol.OriginalDefinition);
public IEnumerable<IType> TypeArguments => TypeCollection.CreateTypeArguments(symbol);
public override string Name
{
Expand Down
5 changes: 5 additions & 0 deletions NTypewriter.CodeModel/IType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@ public interface IType : ISymbolBase
/// </summary>
IType ArrayType { get; }

/// <summary>
/// The original definition of the type, or the type itself if not generic.
/// </summary>
IType OriginalDefinition { get; }

/// <summary>
/// The set of interfaces that this type directly implements. This set does not include interfaces that are base interfaces of directly implemented interfaces.
/// </summary>
Expand Down
12 changes: 12 additions & 0 deletions Tests.Assets.WebApi/Assets/ArrayDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.Collections.Generic;

namespace Tests.Assets.WebApi.Controllers
{
public class ArrayDTO
{
public string[] ArrayStr { get; set; }
public List<string> ListStr { get; set; }
public NumbersEnum[] ArrayEnum { get; set; }
public List<NumbersEnum> ListEnum { get; set; }
}
}
13 changes: 13 additions & 0 deletions Tests.Assets.WebApi/Assets/NullableArrayDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#nullable enable
using System.Collections.Generic;

namespace Tests.Assets.WebApi.Controllers
{
public class NullableArrayDTO
{
public string[]? ArrayStr { get; set; }
public List<string>? ListStr { get; set; }
public NumbersEnum[]? ArrayEnum { get; set; }
public List<NumbersEnum>? ListEnum { get; set; }
}
}
26 changes: 25 additions & 1 deletion Tests.Assets.WebApi/Controllers/UrlController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,29 @@ public IActionResult WithOptionalParam(int? optional)
{
return null;
}

[HttpGet("object-param")]
public IActionResult WithOptionalObjectParam([FromQuery] WeatherForecast optional = null)
{
return null;
}

[HttpGet("array-param")]
public IActionResult WithArrayParam([FromQuery] string[] array)
{
return null;
}

[HttpGet("array-in-object-param")]
public IActionResult WithArrayInObjectParam([FromQuery] ArrayDTO optional = null)
{
return null;
}

[HttpGet("nullable-array-in-object-param")]
public IActionResult WithNullableArrayInObjectParam([FromQuery] NullableArrayDTO optional = null)
{
return null;
}
}
}
}
Loading