Search code examples
c#swagger-codegenhandlebars.net

Changing the name of a generated data model property in swagger-codegen


I am generating a data model using swagger-codegen. The template

/// <summary>
/// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}}
/// </summary>{{#description}}
/// <value>{{description}}</value>{{/description}}
[JsonProperty("{{baseName}}")]
public {{{datatype}}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; }

generates

/// <summary>
/// Description of property.
/// </summary>
/// <value>Description of property.</value>
[JsonProperty("property_name")]
public String property_name { get; set; }

How can I change the case of the property name from snake_case to PascalCase? I imagine I have to do some kind of transformation to {{name}} but I'm not very familiar with handlebars templates.

/// <summary>
/// Description of property.
/// </summary>
/// <value>Description of property.</value>
[JsonProperty("property_name")]
public String PropertyName { get; set; }

Solution

  • I don't know if there's anything built into Swagger Codegen, but with handlebars.net, you can register a helper to convert the string to PascalCase:

    Handlebars.RegisterHelper("PascalCase", (writer, context, parameters) => {
      // paramaters[0] should be name, convert it to PascalCase here
    });
    

    My c# is dusty enough that I don't remember if there is a builtin way of PascalCasing a string, but it shouldn't be too hard to do if there isn't.

    Then call it from your template:

    public {{{datatype}}} {{PascalCase name}} ...
    

    Edit: It looks like Swagger Codegen uses jmustache under the hood, and from a quick glance, but I think you can do something similar with Lambdas