Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate constructors in swagger codegen?

The codegen did not generate any constructor. I referred to petstore swagger file, used latest swagger codegen jar file.

But only default constructor was generated.

It is not generating constructor based on its fields.

How to enable it?

like image 764
a3.14_Infinity Avatar asked Aug 19 '17 05:08

a3.14_Infinity


2 Answers

If you really need a constructor with parameters you can do so by modifying the template file(s) that end with .moustache.

"enable/use/modify" templates

I'm going to assume you're going to be editing an existing template and want a constructor for each model.

Here is a simple example of a constructor inside the model template file:

public {{classname}}( {{#vars}} {{datatype}} {{baseName}}{{^-last}},{{/-last}} {{#-last}}){
construct code here
}{{/-last}}{{/vars}}

note that this should go between the {{#model}} {{/model}} tags

for more information about the moustache templates refer to

https://mustache.github.io/mustache.5.html

List of template variables

template examples for the codegen

like image 54
Viktor Baert Avatar answered Sep 19 '22 14:09

Viktor Baert


I would first like to thank @Viktor Baert for his answer. While the answer provided direction it didn't provide enough to solve it. Note a change and an addition to the answer above.

The change is from {{datatype}} to {{{datatypeWithEnum}}} in the the constructor signature. This change will support any properties that use generics e.g List.

The second is the inclusion of the assignment of the parameters to the local variables.

When these changes are applied to pojo.mustache either directly or overriding the result is the generation of a usable constructor. This works with both the swagger and openapi generators.

public {{classname}}( {{#vars}} {{{datatypeWithEnum}}} {{baseName}}{{^-last}},{{/-last}} {{#-last}}){
  {{#vars}}
  this.{{baseName}} = {{baseName}};
  {{/vars}}
}{{/-last}}{{/vars}}

Reference:add constructors to code generated by openapi codegen

like image 41
TomRed Avatar answered Sep 20 '22 14:09

TomRed