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 項目一起使用,但是其思路可以參考。
代碼生成無非就是找出重復代碼的規律,將其中變化的部分定義出來,然后通過模板來生成不同的代碼。
通過模板來生成代碼,跟拷貝相似代碼來修改相比,可以有效減少很多人為造成的混亂,比如拷貝過來后漏改,或者有些多余代碼未刪除等等。