Skip to content

feat: allow head method for MapQuery() #106

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

Merged
merged 1 commit into from
Jun 13, 2023
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
25 changes: 19 additions & 6 deletions src/Cnblogs.Architecture.Ddd.Cqrs.AspNetCore/CqrsRouteMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,16 @@ public static class CqrsRouteMapper

private static readonly List<Type> CommandTypes = new() { typeof(ICommand<>), typeof(ICommand<,>) };

private static readonly string[] GetAndHeadMethods = { "GET", "HEAD" };

/// <summary>
/// Map a query API, using GET method. <typeparamref name="T"/> would been constructed from route and query string.
/// </summary>
/// <param name="app"><see cref="IApplicationBuilder"/></param>
/// <param name="route">The route template for API.</param>
/// <param name="mapNullableRouteParameters">Multiple routes should be mapped when for nullable route parameters.</param>
/// <param name="nullRouteParameterPattern">Replace route parameter with given string to represent null.</param>
/// <param name="enableHead">Map HEAD method for the same routes.</param>
/// <typeparam name="T">The type of the query.</typeparam>
/// <returns></returns>
/// <example>
Expand All @@ -44,13 +47,15 @@ public static IEndpointConventionBuilder MapQuery<T>(
this IEndpointRouteBuilder app,
[StringSyntax("Route")] string route,
MapNullableRouteParameter mapNullableRouteParameters = MapNullableRouteParameter.Disable,
string nullRouteParameterPattern = "-")
string nullRouteParameterPattern = "-",
bool enableHead = false)
{
return app.MapQuery(
route,
([AsParameters] T query) => query,
mapNullableRouteParameters,
nullRouteParameterPattern);
nullRouteParameterPattern,
enableHead);
}

/// <summary>
Expand All @@ -61,6 +66,7 @@ public static IEndpointConventionBuilder MapQuery<T>(
/// <param name="handler">The delegate that returns a <see cref="IQuery{TView}"/> instance.</param>
/// <param name="mapNullableRouteParameters">Multiple routes should be mapped when for nullable route parameters.</param>
/// <param name="nullRouteParameterPattern">Replace route parameter with given string to represent null.</param>
/// <param name="enableHead">Allow HEAD for the same routes.</param>
/// <returns></returns>
/// <example>
/// The following code:
Expand All @@ -80,7 +86,8 @@ public static IEndpointConventionBuilder MapQuery(
[StringSyntax("Route")] string route,
Delegate handler,
MapNullableRouteParameter mapNullableRouteParameters = MapNullableRouteParameter.Disable,
string nullRouteParameterPattern = "-")
string nullRouteParameterPattern = "-",
bool enableHead = false)
{
var isQuery = handler.Method.ReturnType.GetInterfaces().Where(x => x.IsGenericType)
.Any(x => QueryTypes.Contains(x.GetGenericTypeDefinition()));
Expand All @@ -92,7 +99,7 @@ public static IEndpointConventionBuilder MapQuery(

if (mapNullableRouteParameters is MapNullableRouteParameter.Disable)
{
return app.MapGet(route, handler).AddEndpointFilter<QueryEndpointHandler>();
return MapRoutes(route);
}

if (string.IsNullOrWhiteSpace(nullRouteParameterPattern))
Expand Down Expand Up @@ -125,10 +132,16 @@ public static IEndpointConventionBuilder MapQuery(
var regex = new Regex("{" + x.Name + "[^}]*?}", RegexOptions.IgnoreCase);
return regex.Replace(r, nullRouteParameterPattern);
});
app.MapGet(newRoute, handler).AddEndpointFilter<QueryEndpointHandler>();
MapRoutes(newRoute);
}

return app.MapGet(route, handler).AddEndpointFilter<QueryEndpointHandler>();
return MapRoutes(route);

IEndpointConventionBuilder MapRoutes(string r)
{
var endpoint = enableHead ? app.MapMethods(r, GetAndHeadMethods, handler) : app.MapGet(r, handler);
return endpoint.AddEndpointFilter<QueryEndpointHandler>();
}
}

/// <summary>
Expand Down
23 changes: 23 additions & 0 deletions src/Cnblogs.Architecture.Ddd.Cqrs.ServiceAgent/CqrsServiceAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,29 @@ public async Task<CommandResponse<TResponse, ServiceAgentError>> PutCommandAsync
}
}

/// <summary>
/// Query item with HEAD method.
/// </summary>
/// <param name="url">The route of the API.</param>
/// <returns>True if status code is 2xx, False if status code is 404.</returns>
public async Task<bool> HasItemAsync(string url)
{
var request = new HttpRequestMessage(HttpMethod.Head, url);
var response = await HttpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
return true;
}

if (response.StatusCode == HttpStatusCode.NotFound)
{
return false;
}

response.EnsureSuccessStatusCode(); // throw for other status code
return false;
}

/// <summary>
/// Batch get items with GET method.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@

var apis = app.NewVersionedApi();
var v1 = apis.MapGroup("/api/v{version:apiVersion}").HasApiVersion(1);
v1.MapQuery<GetStringQuery>("apps/{appId}/strings/{stringId:int}/value", MapNullableRouteParameter.Enable);
v1.MapQuery<GetStringQuery>("apps/{appId}/strings/{stringId:int}/value", MapNullableRouteParameter.Enable, enableHead: true);
v1.MapQuery<GetStringQuery>("strings/{id:int}");
v1.MapQuery<ListStringsQuery>("strings");
v1.MapCommand("strings", (CreatePayload payload) => new CreateCommand(payload.NeedError));
Expand Down
22 changes: 22 additions & 0 deletions test/Cnblogs.Architecture.IntegrationTests/CqrsRouteMapperTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,26 @@ await builder.CreateClient().GetAsync("/api/v1/apps/someApp/strings/1/value")
// Assert
responses.Should().Match(x => x.All(y => y.IsSuccessStatusCode));
}

[Fact]
public async Task GetItem_MapHeadAndGet_SuccessAsync()
{
// Arrange
var builder = new WebApplicationFactory<Program>();

// Act
var uris = new[]
{
"/api/v1/apps/-/strings/-/value", "/api/v1/apps/-/strings/1/value",
"/api/v1/apps/someApp/strings/-/value", "/api/v1/apps/someApp/strings/1/value"
}.Select(x => new HttpRequestMessage(HttpMethod.Head, x));
var responses = new List<HttpResponseMessage>();
foreach (var uri in uris)
{
responses.Add(await builder.CreateClient().SendAsync(uri, HttpCompletionOption.ResponseHeadersRead));
}

// Assert
responses.Should().Match(x => x.All(y => y.IsSuccessStatusCode));
}
}