Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define enum values in String using Swagger Codegen

I am using SwaggerCodegen(2.3.1) to generate the client code of my APIs. I've used enum as part of YAML definition file, after which Swagger generates the java file.

random:
    enum:
    - A
    - B
    - C+
    - C-
    type: string

This yml gets converted to

  public enum Random{
    A("A"),
   B("B"),
   C_("C+"),
   C_("C-"); // compile time error..

private String value;
....}

Is there a way I can give a name to my enum values like below ?

public enum Random{
A("A"),
B("B"),
CP("C+"),  
CM("C-"); 
}
like image 685
Himanshu Arora Avatar asked Oct 17 '22 14:10

Himanshu Arora


1 Answers

Special Characters is a restriction to swagger codegen and may be they're still not supported so to achieve it I have to add a new block in the yml file

random:
enum:
- A
- B
- C+
- C-
x-enum-names:
- A
- B
- CP
- CM
type: string

and along with this I've to create a class that inherits JavaClientCodegen and override below method which will replace C+ to CP

class SwaggerCodegen : JavaClientCodegen() {
 override fun updateCodegenPropertyEnum(codegenProperty: CodegenProperty?) {
      super.updateCodegenPropertyEnum(codegenProperty)
      if (codegenProperty!!.vendorExtensions.containsKey( "x-enum-names" )) {
         val alterNames = codegenProperty.vendorExtensions["x-enum-names"] as List<String>
         val enums = codegenProperty.allowableValues.get("enumVars") as List<MutableMap<String, String>>
         if (alterNames.size != enums.size) {
            return
         }
         alterNames.forEachIndexed { index, element ->
            enums[index].put("name", element)
         }
      }
   }
}
like image 172
Himanshu Arora Avatar answered Oct 21 '22 00:10

Himanshu Arora