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

Use IValidateOptions<T> to validate the options created #79

Merged
merged 2 commits into from
Apr 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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