Skip to content

Byndyusoft/Byndyusoft.ModelResult

Repository files navigation

Byndyusoft.ModelResult

The result of domain logic, similar to ActionResult

Byndyusoft.ModelResult Nuget Downloads
Byndyusoft.ModelResult.AspNetCore Nuget Downloads

Installing

dotnet add package Byndyusoft.ModelResult

Usage

ModelResult can be used to return either an "ok" value or an "error" value without explicit casting. Here are some usage examples:

public ModelResult<int> GetId(SampleEntity entity)
{
    if (entity.HasId())
        return entity.Id;

    return new ErrorModelResult("Project.SampleEntity.NoId", "Entity does not contain Id");
}

public ModelResult ValidateEntity(SampleEntity entity)
{
    var errorInfoItems = new List<ErrorInfoItem>();

    if (entity.HasId() == false)
        errorInfoItems.Add(new ErrorInfoItem("Id", "Entity does not contain Id"));

    if (errorInfoItems.Any())
        return new ErrorModelResult("Project.SampleEntity.NotValid", "There are validation errors", errorInfoItems.ToArray());

    return new OkModelResult();
}

public ModelResult<EntityInfoDto> GetEntityInfoDto(SampleEntity entity)
{
    ModelResult<int> idResult = GetId(entity);

    if (idResult.IsError())
    {
        _logger.LogError("Error getting id: {@ErrorInfo}", idResult.GetError());
        return idResult.AsSimple();
    }

    var entityInfoDto = new EntityInfoDto {Id = idResult.Result};
    return entityInfoDto;
}

ModelResult.AspNetCore

A converter of ModelResult to ActionResult

Installing

dotnet add package Byndyusoft.ModelResult.AspNetCore

Usage

[HttpGet("{id:long}")]
public async Task<ActionResult<EntityInfoDto>> GetEntityInfoDto([FromRoute] long id,
    [FromServices] IGetEntityInfoDtoUseCase useCase, CancellationToken cancellationToken)
{
    var result = await useCase.GetAsync(id, cancellationToken);
    return result.ToActionResult();
}

If result is an "ok" result then the action method will return a message with the 200 code and the contents of the DTO. Otherwise if it is "error" result it is usually will be transformed to 400 code with error info that contains code, message and items. The current version has one exception: if an error code is equal to Byndyusoft.ModelResult.Common.CommonErrorCodes.NotFound there will be the 404 code without any content.

Contributing

To contribute, you will need to setup your local environment, see prerequisites. For a contribution and workflow guide, see package development lifecycle.

A detailed overview on how to contribute can be found in the contributing guide.

Prerequisites

Make sure you have installed all of the following prerequisites on your development machine:

Package development lifecycle

  • Implement package logic in src
  • Add or adapt unit-tests in tests
  • Add or change the documentation as needed
  • Open pull request for a correct branch. Target the project's master branch

Maintainers

github.maintain@byndyusoft.com