Skip to content

Commit

Permalink
refactor: Get language options from the constructor to avoid memory r…
Browse files Browse the repository at this point in the history
…eallocations (#255)
  • Loading branch information
MrDave1999 authored Jul 1, 2024
1 parent d1adc3d commit 9e460be
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/HostApplication/Extensions/SwaggerGen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,21 @@ public static IServiceCollection AddSwagger(this IServiceCollection services)

private class AcceptLanguageHeaderParameter(IConfiguration configuration) : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
private readonly IList<IOpenApiAny> _languageOptions = CreateLanguageOptions(configuration);
private readonly string _defaultLanguage = configuration.GetDefaultLanguage();

private static List<IOpenApiAny> CreateLanguageOptions(IConfiguration configuration)
{
operation.Parameters ??= [];
var languageOptions = new List<IOpenApiAny>();
var languages = configuration.GetLanguages();
var defaultLanguage = configuration.GetDefaultLanguage();
foreach (var language in languages)
foreach (var language in languages)
languageOptions.Add(new OpenApiString(language));
return languageOptions;
}

public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
operation.Parameters ??= [];
operation.Parameters.Add(new OpenApiParameter
{
Name = "Accept-Language",
Expand All @@ -66,8 +72,8 @@ public void Apply(OpenApiOperation operation, OperationFilterContext context)
Schema = new OpenApiSchema
{
Type = "string",
Default = new OpenApiString(defaultLanguage),
Enum = languageOptions
Default = new OpenApiString(_defaultLanguage),
Enum = _languageOptions
}
});
}
Expand Down

0 comments on commit 9e460be

Please sign in to comment.