生成 Kotlin service 例子

.templates.tpl.js 中添加 handlebars 自定义钩子

// templates 注入 例子。 不能使用 js 高级语法。
// 插件官方说明文档: http://niuhe.zuxing.net/chapter4/section6.html
// handlebars详细例子参考 https://handlebarsjs.com/zh/

handlebars.registerHelper("convertKtType", function (type) {
  const typeMap = {
    string: "String",
    stringenum: "String",
    number: "Int",
    float: "Float",
    double: "Double",
    int: "Int",
    long: "Long",
    enum: "Int",
    integer: "Int",
    boolean: "Boolean",
    object: "Any",
    array: "List<Any>",
    map: "Map<String, Any>",
  };
  return typeMap[type] || type || "--";
});

// 大写
handlebars.registerHelper("upperCase", function (args) {
  if(!args) {
    return args;
  }
  return args.toUpperCase();
});

handlebars.registerHelper("formType", function (method) {
  if(method === "POST" || method === "post") {
    return "@Field";
  }
  return "@Query";
});

handlebars.registerHelper("shouldUrlEncode", function (method) {
  if(method === "POST" || method === "post") {
    return this.req && this.req.fields.length>0;
  }
  return false;
});

template 编写

package your_package

import your_package.model.*
import retrofit2.Response
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
import retrofit2.http.GET
import retrofit2.http.Query

{{!-- 模板使用到的自定义钩子: convertKtType, shouldEncode, formType, upperCase }} --}}
interface ApiService {
 {{#each items}}

{{#if desc}}
    /** {{desc}} */
{{/if}}
{{#if (shouldUrlEncode method)}}
    @FormUrlEncoded
{{/if}}
    @{{upperCase method}}("{{url}}")
    suspend fun {{name}}(
        {{#each req.fields}}
        {{#if desc}}
        /** {{desc}} */
        {{/if}}
        {{#if (isArray label)}}
        {{formType ../method}}("{{ json }}") {{ name }}: List<{{ convertKtType type }}>,
        {{else}}
        {{formType ../method}}("{{ json }}") {{ name }}: {{ convertKtType type }},
        {{/if}}
        {{/each}}
    ): Response<Rsp<{{rsp.name}}>>
{{/each}}
}

.config.json5 参考配置

 {
    templates: [{
      modes: ["api"],
      template: "./templates/kt_route.tpl",
      type: "route",
      output: "./output/ApiService.kt",
    }]
 }