golang 標準庫template的程式碼生成
curd-gen 專案
curd-gen 專案的建立本來是為了做為 illuminant 專案的一個工具,用來生成前端增刪改查頁面中的基本程式碼。
最近,隨著 antd Pro v5 的升級,將專案進行了升級,現在生成的都是 ts 程式碼。
這個專案的自動生成程式碼都是基於 golang 的標準庫 template 的,所以這篇部落格也算是對使用 template 庫的一次總結。
自動生成的配置
curd-gen 專案的自動程式碼生成主要是3部分:
- 型別定義:用於API請求和頁面顯示的各個型別
- API請求:graphql 請求語句和函式
- 頁面:列表頁面,新增頁面和編輯頁面。新增和編輯是用彈出 modal 框的方式。
根據要生成的內容,定義了一個json格式檔案,做為程式碼生成的基礎。
json檔案的說明在:https://gitee.com/wangyubin/curd-gen#curdjson
生成型別定義
型別是API請求和頁面顯示的基礎,一般開發流程也是先根據業務定義型別,才開始API和頁面的開發的。
自動生成型別定義就是根據 json 檔案中的欄位列表,生成 ts 的型別定義。
模板定義如下:
const TypeDTmpl = `// @ts-ignore /* eslint-disable */ declare namespace API { type {{.Model.Name}}Item = { {{- with .Model.Fields}} {{- range .}} {{- if .IsRequired}} {{.Name}}: {{.ConvertTypeForTs}}; {{- else}} {{.Name}}?: {{.ConvertTypeForTs}}; {{- end}}{{- /* end for if .IsRequired */}} {{- end}}{{- /* end for range */}} {{- end}}{{- /* end for with .Model.Fields */}} }; type {{.Model.Name}}ListResult = CommonResponse & { data: { {{.Model.GraphqlName}}: {{.Model.Name}}Item[]; {{.Model.GraphqlName}}_aggregate: { aggregate: { count: number; }; }; }; }; type Create{{.Model.Name}}Result = CommonResponse & { data: { insert_{{.Model.GraphqlName}}: { affected_rows: number; }; }; }; type Update{{.Model.Name}}Result = CommonResponse & { data: { update_{{.Model.GraphqlName}}_by_pk: { id: string; }; }; }; type Delete{{.Model.Name}}Result = CommonResponse & { data: { delete_{{.Model.GraphqlName}}_by_pk: { id: string; }; }; }; }`
除了主要的型別,還包括了增刪改查 API 返回值的定義。
其中用到 text/template 庫相關的知識點有:
- 通過 **with **限制訪問範圍,這樣,在 {{- with xxx}} 和 {{- end}} 的程式碼中,不用每個欄位前再加 .Model.Fields 字首了
- 通過 range 迴圈訪問陣列,根據陣列中每個元素來生成相應的程式碼
- 通過 if 判斷,根據json檔案中的屬性的不同的定義生成不同的程式碼
- 自定義函式 **ConvertTypeForTs **,這個函式是將json中定義的 graphql type 轉換成 typescript 中對應的型別。用自定義函式是為了避免在模板中寫過多的邏輯程式碼
生成API
這裡只生成 graphql 請求的 API,是為了配合 illuminant 專案。
API的引數和返回值用到的物件就在上面自動生成的型別定義中。
const APITmpl = `// @ts-ignore
/* eslint-disable */
import { Graphql } from '../utils';
const gqlGet{{.Model.Name}}List = ` + "`" + `query get_item_list($limit: Int = 10, $offset: Int = 0{{- with .Model.Fields}}{{- range .}}{{- if .IsSearch}}, ${{.Name}}: {{.Type}}{{- end}}{{- end}}{{- end}}) {
{{.Model.GraphqlName}}(order_by: {updated_at: desc}, limit: $limit, offset: $offset{{.Model.GenGraphqlSearchWhere false}}) {
{{- with .Model.Fields}}
{{- range .}}
{{.Name}}
{{- end}}
{{- end}}
}
{{.Model.GraphqlName}}_aggregate({{.Model.GenGraphqlSearchWhere true}}) {
aggregate {
count
}
}
}` + "`" + `;
const gqlCreate{{.Model.Name}} = ` + "`" + `mutation create_item({{.Model.GenGraphqlInsertParamDefinations}}) {
insert_{{.Model.GraphqlName}}(objects: { {{.Model.GenGraphqlInsertParams}} }) {
affected_rows
}
}` + "`" + `;
const gqlUpdate{{.Model.Name}} = ` + "`" + `mutation update_item_by_pk($id: uuid!, {{.Model.GenGraphqlUpdateParamDefinations}}) {
update_{{.Model.GraphqlName}}_by_pk(pk_columns: {id: $id}, _set: { {{.Model.GenGraphqlUpdateParams}} }) {
id
}
}` + "`" + `;
const gqlDelete{{.Model.Name}} = ` + "`" + `mutation delete_item_by_pk($id: uuid!) {
delete_{{.Model.GraphqlName}}_by_pk(id: $id) {
id
}
}` + "`" + `;
export async function get{{.Model.Name}}List(params: API.{{.Model.Name}}Item & API.PageInfo) {
const gqlVar = {
limit: params.pageSize ? params.pageSize : 10,
offset: params.current && params.pageSize ? (params.current - 1) * params.pageSize : 0,
{{- with .Model.Fields}}
{{- range .}}
{{- if .IsSearch}}
{{.Name}}: params.{{.Name}} ? '%' + params.{{.Name}} + '%' : '%%',
{{- end}}
{{- end}}
{{- end}}
};
return Graphql<API.{{.Model.Name}}ListResult>(gqlGet{{.Model.Name}}List, gqlVar);
}
export async function create{{.Model.Name}}(params: API.{{.Model.Name}}Item) {
const gqlVar = {
{{- with .Model.Fields}}
{{- range .}}
{{- if not .NotInsert}}
{{- if .IsPageRequired}}
{{.Name}}: params.{{.Name}},
{{- else}}
{{.Name}}: params.{{.Name}} ? params.{{.Name}} : null,
{{- end}}
{{- end}}
{{- end}}
{{- end}}
};
return Graphql<API.Create{{.Model.Name}}Result>(gqlCreate{{.Model.Name}}, gqlVar);
}
export async function update{{.Model.Name}}(params: API.{{.Model.Name}}Item) {
const gqlVar = {
id: params.id,
{{- with .Model.Fields}}
{{- range .}}
{{- if not .NotUpdate}}
{{- if .IsPageRequired}}
{{.Name}}: params.{{.Name}},
{{- else}}
{{.Name}}: params.{{.Name}} ? params.{{.Name}} : null,
{{- end}}
{{- end}}
{{- end}}
{{- end}}
};
return Graphql<API.Update{{.Model.Name}}Result>(gqlUpdate{{.Model.Name}}, gqlVar);
}
export async function delete{{.Model.Name}}(id: string) {
return Graphql<API.Delete{{.Model.Name}}Result>(gqlDelete{{.Model.Name}}, { id });
}`
這個模板中也使用了幾個自定義函式,GenGraphqlSearchWhere,GenGraphqlInsertParams,**GenGraphqlUpdateParams **等等。
生成列表頁面,新增和編輯頁面
最後一步,就是生成頁面。列表頁面是主要頁面:
const PageListTmpl = `import { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Modal, Popconfirm, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { get{{.Model.Name}}List, create{{.Model.Name}}, update{{.Model.Name}}, delete{{.Model.Name}} } from '{{.Page.ApiImport}}';
import {{.Model.Name}}Add from './{{.Model.Name}}Add';
import {{.Model.Name}}Edit from './{{.Model.Name}}Edit';
export default () => {
const tableRef = useRef<ActionType>();
const [modalAddVisible, setModalAddVisible] = useState(false);
const [modalEditVisible, setModalEditVisible] = useState(false);
const [record, setRecord] = useState<API.{{.Model.Name}}Item>({});
const columns: ProColumns<API.{{.Model.Name}}Item>[] = [
{{- with .Model.Fields}}
{{- range .}}
{{- if .IsColumn}}
{
title: '{{.Title}}',
dataIndex: '{{.Name}}',
{{- if not .IsSearch}}
hideInSearch: true,
{{- end}}
},
{{- end }}{{- /* end for if .IsColumn */}}
{{- end }}{{- /* end for range . */}}
{{- end }}{{- /* end for with */}}
{
title: '操作',
valueType: 'option',
render: (_, rd) => [
<Button
type="primary"
size="small"
key="edit"
onClick={() => {
setModalEditVisible(true);
setRecord(rd);
}}
>
修改
</Button>,
<Popconfirm
placement="topRight"
title="是否刪除?"
okText="Yes"
cancelText="No"
key="delete"
onConfirm={async () => {
const response = await delete{{.Model.Name}}(rd.id as string);
if (response.code === 10000) message.info(` + "`" + `TODO: 【${rd.TODO}】 刪除成功` + "`" + `);
else message.warn(` + "`" + `TODO: 【${rd.TODO}】 刪除失敗` + "`" + `);
tableRef.current?.reload();
}}
>
<Button danger size="small">
刪除
</Button>
</Popconfirm>,
],
},
];
const addItem = async (values: any) => {
console.log(values);
const response = await create{{.Model.Name}}(values);
if (response.code !== 10000) {
message.error('建立TODO失敗');
}
if (response.code === 10000) {
setModalAddVisible(false);
tableRef.current?.reload();
}
};
const editItem = async (values: any) => {
values.id = record.id;
console.log(values);
const response = await update{{.Model.Name}}(values);
if (response.code !== 10000) {
message.error('編輯TODO失敗');
}
if (response.code === 10000) {
setModalEditVisible(false);
tableRef.current?.reload();
}
};
return (
<PageContainer fixedHeader header={{"{{"}} title: '{{.Page.Title}}' }}>
<ProTable<API.{{.Model.Name}}Item>
columns={columns}
rowKey="id"
actionRef={tableRef}
search={{"{{"}}
labelWidth: 'auto',
}}
toolBarRender={() => [
<Button
key="button"
icon={<PlusOutlined />}
type="primary"
onClick={() => {
setModalAddVisible(true);
}}
>
新建
</Button>,
]}
request={async (params: API.{{.Model.Name}}Item & API.PageInfo) => {
const resp = await get{{.Model.Name}}List(params);
return {
data: resp.data.{{.Model.GraphqlName}},
total: resp.data.{{.Model.GraphqlName}}_aggregate.aggregate.count,
};
}}
/>
<Modal
destroyOnClose
title="新增"
visible={modalAddVisible}
footer={null}
onCancel={() => setModalAddVisible(false)}
>
<{{.Model.Name}}Add onFinish={addItem} />
</Modal>
<Modal
destroyOnClose
title="編輯"
visible={modalEditVisible}
footer={null}
onCancel={() => setModalEditVisible(false)}
>
<{{.Model.Name}}Edit onFinish={editItem} record={record} />
</Modal>
</PageContainer>
);
};`
新增頁面和編輯頁面差別不大,分開定義是為了以後能分別擴充套件。
新增頁面:
const PageAddTmpl = `import ProForm, {{.Model.GenPageImportCtrls}}
import { formLayout } from '@/common';
import { Row, Col, Space } from 'antd';
export default (props: any) => {
return (
<ProForm
{...formLayout}
layout="horizontal"
onFinish={props.onFinish}
submitter={{"{{"}}
// resetButtonProps: { style: { display: 'none' } },
render: (_, dom) => (
<Row>
<Col offset={10}>
<Space>{dom}</Space>
</Col>
</Row>
),
}}
>
{{- with .Model.Fields}}
{{- range .}}
{{- .GenPageCtrl}}
{{- end}}
{{- end}}
</ProForm>
);
};`
頁面生成中有個地方困擾了我一陣,就是頁面中有個和 text/template 標記衝突的地方,也就是 {{ 的顯示。
比如上面的 submitter={{"{{"}} ,頁面中需要直接顯示 {{ 2個字元,但 {{ }} 框住的部分是模板中需要替換的部分。
所以,模板中需要顯示 {{ 的地方,可以用 {{"{{"}} 代替。
總結
上面的程式碼生成雖然需要配合 illuminant 專案一起使用,但是其思路可以參考。
程式碼生成無非就是找出重複程式碼的規律,將其中變化的部分定義出來,然後通過模板來生成不同的程式碼。
通過模板來生成程式碼,跟拷貝相似程式碼來修改相比,可以有效減少很多人為造成的混亂,比如拷貝過來後漏改,或者有些多餘程式碼未刪除等等。