-
Notifications
You must be signed in to change notification settings - Fork 424
Adding a new generator for a language or framework.
I'm going to take the JavascriptClientCodegen
generator as example. I'm assuming that developer is familiar with handlebars and/or mustaches templates.
So, the first step is create a class and extend it from DefaultCodegenConfig
public class JavaScriptClientCodegen extends DefaultCodegenConfig
We are asked to override getName
, getDefaultTemplateDir
, getHelp
and getTag
method.
-
getName
: returns the name assigned to generator to be used on CLI along with the--lang
option. -
getDefaultTemplateDir
: to specify template directory name,javascript
in this case -
geTag
: use it to specify if output code is a client, server, documentation or other project, eample:CodegenType.CLIENT
. -
geHelp
: A short description of the output your generator does, i.e:Generates a Javascript client library
.
To generate code we need to work with templates (currently supported engines: Handlebars and mustaches) and codegen pojos.
Templates are placed at:
-
src/main/resources/handlerbars
- for handlebars templates. SogetDefaultTemplateDir
will point to"src/main/resources/handlerbars/javascript"
, in our example. -
src/main/resources/mustache
- for mustache templates.
- CodegenModel: represents an OpenAPI schema located at: components/schemas
- CodegenProperty: represents a schema as property inside a model.
- CodegenParameter: represents parameter schema or a request body schema prenset in a operation.
- CodegenOperation: represents an OpenAPI operation.
These pojos are used in templates such as api.mustache
and models.mustache
to render any data configured on them.
Most of the logic for code generation is present in DefaultCodegenConfig
class. However to apply a specific behave most of the generators used to override their methods. Some key methods are listed next:
-
fromModel
: To create codegen models objects to be rendered later in templates. -
fromProperty
: To create codegen property. -
fromParameter
: To create codegen parameter. -
getSchemaType
: This important to define types related to a language. It uses to be overrided most of the cases. -
processOpts
: To handle any additional option or configuration for code generation.
Some properties to keep in mind on your generator class:
-
modelTemplateFiles
: add here any model templates you want to write. In our example:
modelTemplateFiles.put("model.mustache", ".js");
-
apiTemplateFiles
: add here any model templates you want to write. In our example:
apiTemplateFiles.put("api.mustache", ".js");
Another key step is to add the new generator class to: modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig
To see full implementation of this i recommend to check this PR for javascript generator.