RicoSuter / NSwag

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

PropertyNameGenerator: add passing and failing tests demonstrating issue with CodeGeneration #4711

Open johnnyreilly opened 8 months ago

johnnyreilly commented 8 months ago

As mentioned here: https://github.com/RicoSuter/NSwag/issues/1874#issuecomment-1890400894

I've identified an issue with the TypeScript code generation of clients when using the PropertyNameGenerator property to control naming.

Essentially, when using TypeScriptTypeStyle.Class this is respected. When using TypeScriptTypeStyle.Interface it is ignored. This is illustrated by the enclosing tests, one of which fails; demonstrating the issue.

I'd love to help get this fixed and I figured this was a first step!

I've also added a C# test as well as I thought it'd be useful for coverage.

With the following CustomPropertyNameGenerator we can demostrate the issue.

        class CustomPropertyNameGenerator : NJsonSchema.CodeGeneration.IPropertyNameGenerator {
            public virtual string Generate(JsonSchemaProperty property) => $"XX_{property.Name}";
        }

If this is working as expected, all property names should be prefixed with XX_:

export interface IPerson {
    XX_FirstName: string;
    XX_LastName?: string | undefined;
    XX_Birthday?: Date | undefined;
    XX_Sex?: Sex | undefined;
    XX_Address?: Address | undefined;
}

But if using TypeScriptTypeStyle.Interface it is ignored and instead this is generated:

export interface Person {
    FirstName: string;
    LastName?: string | undefined;
    Birthday?: Date | undefined;
    Sex?: Sex | undefined;
    Address?: Address | undefined;
}

Ideally the CustomPropertyNameGenerator should always be in play.


Having had a dig through the code I wonder if the issue lies in NJsonSchema somewhere:

https://github.com/RicoSuter/NJsonSchema/blob/master/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs https://github.com/RicoSuter/NJsonSchema/blob/3585d60e949e43284601e0bea16c33de4c6c21f5/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGeneratorSettings.cs#L36