Skip to content

Commit 3c6d3be

Browse files
authored
Throw when AddOpenApiForJsonApi is called before AddJsonApi (#1737)
1 parent 86cee8b commit 3c6d3be

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/JsonApiDotNetCore.OpenApi.Swashbuckle/ServiceCollectionExtensions.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using JsonApiDotNetCore.Configuration;
2+
using JsonApiDotNetCore.Errors;
23
using JsonApiDotNetCore.Middleware;
34
using JsonApiDotNetCore.OpenApi.Swashbuckle.JsonApiMetadata;
45
using JsonApiDotNetCore.OpenApi.Swashbuckle.SchemaGenerators;
@@ -23,6 +24,7 @@ public static class ServiceCollectionExtensions
2324
public static void AddOpenApiForJsonApi(this IServiceCollection services, Action<SwaggerGenOptions>? configureSwaggerGenOptions = null)
2425
{
2526
ArgumentNullException.ThrowIfNull(services);
27+
AssertHasJsonApi(services);
2628

2729
AddCustomApiExplorer(services);
2830
AddCustomSwaggerComponents(services);
@@ -38,6 +40,14 @@ public static void AddOpenApiForJsonApi(this IServiceCollection services, Action
3840
services.Replace(ServiceDescriptor.Singleton<IJsonApiApplicationBuilderEvents, OpenApiApplicationBuilderEvents>());
3941
}
4042

43+
private static void AssertHasJsonApi(IServiceCollection services)
44+
{
45+
if (services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(IJsonApiOptions)) == null)
46+
{
47+
throw new InvalidConfigurationException("Call 'services.AddJsonApi()' before calling 'services.AddOpenApiForJsonApi()'.");
48+
}
49+
}
50+
4151
private static void AddCustomApiExplorer(IServiceCollection services)
4252
{
4353
services.TryAddSingleton<OpenApiEndpointConvention>();
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using FluentAssertions;
2+
using JsonApiDotNetCore.Errors;
3+
using JsonApiDotNetCore.OpenApi.Swashbuckle;
4+
using Microsoft.Extensions.DependencyInjection;
5+
using Xunit;
6+
7+
namespace OpenApiTests.OpenApiGenerationFailures.IncorrectSetupOrder;
8+
9+
public sealed class RegistrationTests
10+
{
11+
[Fact]
12+
public void Fails_when_OpenAPI_registered_without_JsonApi()
13+
{
14+
// Arrange
15+
var services = new ServiceCollection();
16+
17+
// Act
18+
Action action = () => services.AddOpenApiForJsonApi();
19+
20+
// Arrange
21+
action.Should().ThrowExactly<InvalidConfigurationException>()
22+
.WithMessage("Call 'services.AddJsonApi()' before calling 'services.AddOpenApiForJsonApi()'.");
23+
}
24+
}

0 commit comments

Comments
 (0)