生成 Kotlin model 例子
.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("ktClass", function (fields) {
if (!fields || fields.length == 0) {
return "class";
}
return "data class";
});
handlebars.registerHelper("shouldSerial", function () {
return this.name !== this.json
});
template 内容
model.tpl 需要生成请求和返回以及引用到的文件定义。 you_package 需修改为你的目标包名
package your_package
import kotlinx.serialization.SerialName
import com.google.gson.annotations.SerializedName
{{!-- 模板使用到的自定义钩子: ktClass, convertKtType, isArray(内置),shouldSerial }} --}}
data class Rsp<T>(
val result: Int,
val data: T?,
val message: String?,
) {
/** 请求成功 */
fun isSuccess(): Boolean {
return result == 0
}
}
{{#each items}}
{{#if desc}}
/** {{desc}} */
{{/if}}
{{ktClass fields}} {{name}}(
{{#each fields}}
{{#if desc}}
/** {{desc}} */
{{/if}}
{{#if (shouldSerial)}}
@SerializedName("{{ json }}")
@SerialName("{{ json }}")
{{/if}}
{{#if (isArray label)}}
val {{ name }}: List<{{ convertKtType type }}>,
{{else}}
val {{ name }}: {{ convertKtType type }},
{{/if}}
{{/each}}
)
{{/each}}
.config.json5 参考配置
{
templates: [{
modes: ["api"],
template: "./templates/kt_message.tpl",
type: "message",
output: "./output/Models.kt",
}]
}