Call Langext MapAsync only if Option is Some value and not None

450 Views Asked by At

I use LangExt library and i have the case of no user exists with UserId 1.

public async Task<Option<UserViewModel> GetUser()
=> await GetUser(1)
          .MapAsync(this.alterName)
          .MapAsync(this.alterCountry)
          .MapAsync(this.applyMoreChange)
          .Map(this.mapper.map<ViewModel>);

since no user exists for userId 1, the GetUser(1) returns Option<None> and the remaining code fails with the exception

LangExt.ValueIsNoneException : Value is None.
at languageExt.OptionAsyncAwaiter`1.GetResult()

How to handle this case.? and to make sure the mapAsync and map chaining execute only if option is some user and not none.

1

There are 1 best solutions below

4
SteveOhByte On

This page on github seems to indicate that option will have a .IfSome() function. The github gives the following code snippet:

// Returns the Some case 'as is' and 10 in the None case
int x = optional.IfNone(10);

// As above, but invokes a Func<T> to return a valid value for x
int x = optional.IfNone(() => GetAlternative());

// Invokes an Action<T> if in the Some state;
optional.IfSome(x => Console.WriteLine(x));

A suggestion on implementation (without knowing the full idea of your project) would be something like this:

public async Task<Option<UserViewModel>> GetUser(int num)
{
    var user = await GetUser(1);
    if (user.IsSome)
    {
        user.MapAsync(this.alterName)
            .MapAsync(this.alterCountry)
            .MapAsync(this.applyMoreChange)
            .Map(this.mapper.map<ViewModel>);

        return user;
    }
}