Skip to content

Instantly share code, notes, and snippets.

@DanteDeRuwe
Created June 14, 2024 07:25
Show Gist options
  • Save DanteDeRuwe/ec89de54fc4badcfb74ef47dcf8b414f to your computer and use it in GitHub Desktop.
Save DanteDeRuwe/ec89de54fc4badcfb74ef47dcf8b414f to your computer and use it in GitHub Desktop.
Map refit ApiResponse to an AspNetCore IResult
public static class ResultMapper
{
/// <summary>
/// A mapper to map to an IResult with potential content
/// </summary>
public static IResult MapToResult<TContent>(this IApiResponse<TContent> response)
{
return response.StatusCode switch
{
HttpStatusCode.OK when response.Content is not null => TypedResults.Ok(response.Content),
_ => MapToResult((IApiResponse)response) // without content
};
}
/// <summary>
/// A mapper to map to an IResult without content
/// </summary>
public static IResult MapToResult(this IApiResponse response)
{
return response.StatusCode switch
{
// Results with extra data
var statusCode when response.Error is ApiException apiException =>TypedResults.Problem(apiException.Message, statusCode: (int)statusCode),
HttpStatusCode.Created => TypedResults.Created(response.Headers.Location),
HttpStatusCode.Accepted when response.Headers.Location is Uri location => TypedResults.Accepted(location),
// All other status code results
_ => TypedResults.StatusCode((int)response.StatusCode)
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment