在使用swagger-codegen生成代码时,我们经常需要使用自定义属性来生成我们需要的代码。swagger-codegen使用了mustache模板引擎来生成代码,而在mustache模板文件中,我们可以通过配置swagger规范文档中的自定义属性来生成我们需要的代码。本篇文章将从第三级标题开始,详细介绍如何在swagger-codegen的mustache模板文件中配置自定义属性。

一、swagger规范文档中的自定义属性

在swagger规范文档中,我们可以通过使用"x-"前缀来定义自定义属性。例如,我们可以在swagger规范文档中定义以下属性:

swagger: ‘2.0’ info: version: 1.0.0 title: Swagger Petstore description: A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification termsOfService: http://swagger.io/terms/ contact: name: Swagger API Team email: apiteam@swagger.io url: http://swagger.io license: name: Apache 2.0 url: http://www.apache.org/licenses/LICENSE-2.0.html host: petstore.swagger.io basePath: /v2 tags:

  • name: pet description: Everything about your Pets x-custom-property: custom value 在上面的示例中,我们定义了一个"x-custom-property"属性,并将其设置为"custom value"。在我们生成代码时,我们可以使用这个属性来生成我们需要的代码。

二、mustache模板文件中的自定义属性

在mustache模板文件中,我们可以通过使用"{{x-custom-property}}"来引用swagger规范文档中定义的自定义属性。例如,我们可以在mustache模板文件中定义以下代码:

{{#operations}} {{#x-custom-property}} // custom property: {{x-custom-property}} {{/x-custom-property}} {{/operations}} 在上面的示例中,我们使用了"x-custom-property"属性来生成我们需要的代码。在我们生成代码时,mustache模板引擎会自动将"x-custom-property"属性替换为我们在swagger规范文档中定义的值。

在swagger规范文档中,我们也可以定义一个API的版本号、作者、创建时间等等。这些属性可以在mustache模板中使用,来生成代码中的注释、类名、方法名等等。下面是一个例子:

swagger: ‘2.0’ info: version: 1.0.0 title: My API description: My API description x-author: John Doe x-created-at: ‘2021-08-01T00:00:00Z’ paths: /users: get: summary: Get a list of users description: Returns a list of users responses: ‘200’: description: A list of users schema: type: array items: $ref: ‘#/definitions/User’ definitions: User: type: object properties: id: type: integer format: int64 name: type: string 在这个例子中,我��定义了两个自定义属性,x-author和x-created-at。我们可以在mustache模板中使用这些属性,比如说我们可以在生成的代码中添加一个注释:

/**

  • Generated by swagger-codegen
  • API version: {{info.version}}
  • Created by {{info[‘x-author’]}} on {{info[‘x-created-at’]}} */ 在这个注释中,我们使用了info.version、info[‘x-author’]和info[‘x-created-at’]三个属性。这些属性在mustache模板中使用时,需要使用双括号来包裹,比如说{{info.version}}。

除了使用自定义属性,我们还可以在mustache模板中使用一些内置的属性,比如说{{apiPackage}}、{{modelPackage}}、{{classname}}等等。这些属性可以帮助我们生成更加灵活的代码。

swagger-codegen的使用方法及常见参数配置 swagger-codegen的模板文件mustache中,classname,description,notes如何赋值