RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.61k stars 1.22k forks source link

Sort keys in OpenAPI specifications #4862

Open varganatt opened 2 months ago

varganatt commented 2 months ago

Thanks for a great library!

When generating an OpenAPI specifications, the paths and components are not sorted in the same order when compiling on Windows vs. Docker. Perhaps the sort order is not specified by NSwag and therefore somewhat arbitrary? That would explain why different instances of .NET cause different outputs.

Feature suggestion: Automatically sort paths and components.

Background for why this is important: I want generation of the OpenAPI spec to be deterministic, so that I more easily can check for unexpected changes.


As a workaround, I have added a document processor:

config.DocumentProcessors.Add(new SortKeysDocumentProcessor());

public class SortKeysDocumentProcessor : IDocumentProcessor
{
    private static void SortKeys<T>(IDictionary<string, T> dictionary)
    {
        var keyValues = dictionary.OrderBy(x => x.Key).ToList();
        dictionary.Clear();
        foreach (var kv in keyValues)
            dictionary.Add(kv.Key, kv.Value);
    }

    public void Process(DocumentProcessorContext context)
    {
        SortKeys(context.Document.Paths);
        SortKeys(context.Document.Components.Schemas);
    }
}