RicoSuter / NSwag

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

Change parameter type #3160

Open lurumad opened 3 years ago

lurumad commented 3 years ago

Hi folks!

I've been working in a library to avoid predictable ids in ASP.NET Core Web APIs https://github.com/Xabaril/AspNetCore.Hashids

I need to change the parameter type to string in the OpenApi specification like I did with Swashbuckle for those types decorated with the HashidsModelBinder (integers):

namespace WebApi
{
    public class HashidsOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var hashids = context
                .ApiDescription
                .ParameterDescriptions
                .Where(x => x.ModelMetadata.BinderType == typeof(HashidsModelBinder))
                .ToDictionary(d => d.Name, d => d);

            foreach (var parameter in operation.Parameters)
            {
                if (hashids.TryGetValue(parameter.Name, out var apiParameter))
                {
                    parameter.Schema.Format = string.Empty;
                    parameter.Schema.Type = "string";
                }
            }

            foreach (var schema in context.SchemaRepository.Schemas.Values)
            {
                foreach (var property in schema.Properties)
                {
                    if (hashids.TryGetValue(property.Key, out var apiParameter))
                    {
                        property.Value.Format = string.Empty;
                        property.Value.Type = "string";
                    }
                }
            }
        }
    }
}

My questions is, are the some mechanisim in nswag in order to transform those types when nswag generates the swagger.json?

Regards!

jeremyVignelles commented 3 years ago

You could use a DocumentProcessor for that, and edit the generated OpenApiSpecification by hand. I'm not sure there is a better way.

RicoSuter commented 3 years ago

I’d use an operation processor (same as your operation filter).