Skip to content
This repository has been archived by the owner on Dec 25, 2024. It is now read-only.

Commit

Permalink
Use IValidateOptions<T> to validate the options created (#79)
Browse files Browse the repository at this point in the history
Use `IValidateOptions<T>` to validate the options created
  • Loading branch information
mburumaxwell authored Apr 8, 2022
1 parent 4d07793 commit 5299af1
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/FaluSdk/Extensions/IServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public static IHttpClientBuilder AddFalu<TClient, TClientOptions>(this IServiceC
}

// register post configuration for validation purposes
services.AddSingleton<IPostConfigureOptions<TClientOptions>, PostConfigureFaluClientOptions<TClientOptions>>();
services.ConfigureOptions<FaluClientConfigureOptions<TClientOptions>>();

// get the version from the assembly
var productVersion = typeof(TClient).Assembly.GetName().Version!.ToString(3);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,30 @@

namespace Falu;

internal class PostConfigureFaluClientOptions<TClientOptions> : IPostConfigureOptions<TClientOptions> where TClientOptions : FaluClientOptions
internal class FaluClientConfigureOptions<TClientOptions> : IPostConfigureOptions<TClientOptions>, IValidateOptions<TClientOptions>
where TClientOptions : FaluClientOptions
{
public void PostConfigure(string name, TClientOptions options)
{
// intentionally left blank for future use
}

public ValidateOptionsResult Validate(string name, TClientOptions options)
{
if (string.IsNullOrWhiteSpace(options.ApiKey))
{
var message = "Your API key is invalid, as it is an empty string. You can "
+ "double-check your API key from the Falu Dashboard. See "
+ "https://docs.falu.io/api/authentication for details or contact support "
+ "at https://falu.com/support/email if you have any questions.";
throw new FaluException(message);
return ValidateOptionsResult.Fail(message);
}

if (options.Retries < 0)
{
throw new FaluException("Retries cannot be negative.");
return ValidateOptionsResult.Fail("Retries cannot be negative.");
}

return ValidateOptionsResult.Success;
}
}
2 changes: 1 addition & 1 deletion tests/FaluSdk.Tests/ServiceCollectionExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public void TestAddFaluWithoutApiKey()
var provider = services.BuildServiceProvider();

// Act && Assert
Assert.Throws<FaluException>(() => provider.GetRequiredService<FaluClient>());
Assert.Throws<OptionsValidationException>(() => provider.GetRequiredService<FaluClient>());
}

[Fact]
Expand Down

0 comments on commit 5299af1

Please sign in to comment.