summaryrefslogtreecommitdiffstats
path: root/server/src/Utilities/SwaggerGenOptionsExtensions.cs
blob: a2dcf7acfb4d0bd92249cd205c27b100fb549cf0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#nullable enable
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Controllers;
using Swashbuckle.AspNetCore.SwaggerGen;
using BaseRoute = IOL.GreatOffice.Api.Endpoints.V1.BaseRoute;

namespace IOL.GreatOffice.Api.Utilities;

public static class SwaggerGenOptionsExtensions
{
	/// <summary>
	/// Updates Swagger document to support ApiEndpoints.<br/><br/>
	/// For controllers inherited from <see cref="BaseRoute"/>:<br/>
	/// - Replaces action Tag with <c>[namespace]</c><br/>
	/// </summary>
	public static void UseApiEndpoints(this SwaggerGenOptions options) {
		options.TagActionsBy(EndpointNamespaceOrDefault);
	}

	private static IList<string?> EndpointNamespaceOrDefault(ApiDescription api) {
		if (api.ActionDescriptor is not ControllerActionDescriptor actionDescriptor) {
			throw new InvalidOperationException($"Unable to determine tag for endpoint: {api.ActionDescriptor.DisplayName}");
		}

		if (actionDescriptor.ControllerTypeInfo.GetBaseTypesAndThis().Any(t => t == typeof(BaseRoute))) {
			return new[] {
					actionDescriptor.ControllerTypeInfo.Namespace?.Split('.').Last()
			};
		}

		return new[] {
				actionDescriptor.ControllerName
		};
	}

	public static IEnumerable<Type> GetBaseTypesAndThis(this Type type) {
		Type? current = type;
		while (current != null) {
			yield return current;
			current = current.BaseType;
		}
	}
}