ardalis / Result

A result abstraction that can be mapped to HTTP response codes if needed.
MIT License
866 stars 107 forks source link

Use with DTOs #94

Closed joncoelloaccess closed 2 years ago

joncoelloaccess commented 2 years ago

Given my aggregates can return a Result of T where T is an entity how do I translate Result of T into a Result of DTO in my API?

I'm trying to incorporate the use of both Result types and avoiding leaking entities

joncoelloaccess commented 2 years ago

I have created my own version of the ToActionResult method which takes an IMapper

        public static ActionResult ToActionResult<T>(this ControllerBase controller, IMapper mapper, Ardalis.Result.IResult result)
        {
            switch (result.Status)
            {
                case ResultStatus.Ok:
                    return typeof(Result).IsInstanceOfType(result)
                        ? (ActionResult)controller.Ok()
                        : controller.Ok(mapper.Map<T>(result.GetValue()));
                case ResultStatus.NotFound: return controller.NotFound();
                case ResultStatus.Unauthorized: return controller.Unauthorized();
                case ResultStatus.Forbidden: return controller.Forbid();
                case ResultStatus.Invalid: return BadRequest(controller, result);
                case ResultStatus.Error: return UnprocessableEntity(controller, result);
                default:
                    throw new NotSupportedException($"Result {result.Status} conversion is not supported.");
            }
        }

I could try to create a PR around this but maybe one that takes a generic Map method to remove the dependency on a specific mapper tech ?