解析golang 標(biāo)準(zhǔn)庫(kù)template的代碼生成方法
curd-gen 項(xiàng)目
curd-gen 項(xiàng)目的創(chuàng)建本來(lái)是為了做為 illuminant 項(xiàng)目的一個(gè)工具,用來(lái)生成前端增刪改查頁(yè)面中的基本代碼。
最近,隨著 antd Pro v5 的升級(jí),將項(xiàng)目進(jìn)行了升級(jí),現(xiàn)在生成的都是 ts 代碼。這個(gè)項(xiàng)目的自動(dòng)生成代碼都是基于 golang 的標(biāo)準(zhǔn)庫(kù) template 的,所以這篇博客也算是對(duì)使用 template 庫(kù)的一次總結(jié)。
自動(dòng)生成的配置
curd-gen 項(xiàng)目的自動(dòng)代碼生成主要是3部分:
- 類型定義:用于API請(qǐng)求和頁(yè)面顯示的各個(gè)類型
- API請(qǐng)求:graphql 請(qǐng)求語(yǔ)句和函數(shù)
- 頁(yè)面:列表頁(yè)面,新增頁(yè)面和編輯頁(yè)面。新增和編輯是用彈出 modal 框的方式。
根據(jù)要生成的內(nèi)容,定義了一個(gè)json格式文件,做為代碼生成的基礎(chǔ)。 json文件的說(shuō)明在:https://gitee.com/wangyubin/curd-gen#curdjson
生成類型定義
類型是API請(qǐng)求和頁(yè)面顯示的基礎(chǔ),一般開發(fā)流程也是先根據(jù)業(yè)務(wù)定義類型,才開始API和頁(yè)面的開發(fā)的。
自動(dòng)生成類型定義就是根據(jù) 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 庫(kù)相關(guān)的知識(shí)點(diǎn)有:
- 通過(guò) **with **限制訪問(wèn)范圍,這樣,在 {{- with xxx}} 和 {{- end}} 的代碼中,不用每個(gè)字段前再加 .Model.Fields 前綴了
- 通過(guò) range 循環(huán)訪問(wèn)數(shù)組,根據(jù)數(shù)組中每個(gè)元素來(lái)生成相應(yīng)的代碼
- 通過(guò) if 判斷,根據(jù)json文件中的屬性的不同的定義生成不同的代碼
- 自定義函數(shù) **ConvertTypeForTs **,這個(gè)函數(shù)是將json中定義的 graphql type 轉(zhuǎn)換成 typescript 中對(duì)應(yīng)的類型。用自定義函數(shù)是為了避免在模板中寫過(guò)多的邏輯代碼
生成API
這里只生成 graphql 請(qǐng)求的 API,是為了配合 illuminant 項(xiàng)目。 API的參數(shù)和返回值用到的對(duì)象就在上面自動(dòng)生成的類型定義中。
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 }); }`
這個(gè)模板中也使用了幾個(gè)自定義函數(shù),GenGraphqlSearchWhere,GenGraphqlInsertParams,**GenGraphqlUpdateParams **等等。
生成列表頁(yè)面,新增和編輯頁(yè)面
最后一步,就是生成頁(yè)面。列表頁(yè)面是主要頁(yè)面:
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('創(chuàng)建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> ); };`
新增頁(yè)面和編輯頁(yè)面差別不大,分開定義是為了以后能分別擴(kuò)展。新增頁(yè)面:
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> ); };`
頁(yè)面生成中有個(gè)地方困擾了我一陣,就是頁(yè)面中有個(gè)和 text/template 標(biāo)記沖突的地方,也就是 {{ 的顯示。比如上面的 submitter={{"{{"}} ,頁(yè)面中需要直接顯示 {{ 2個(gè)字符,但 {{ }} 框住的部分是模板中需要替換的部分。
所以,模板中需要顯示 {{ 的地方,可以用 {{"{{"}} 代替。
總結(jié)
上面的代碼生成雖然需要配合 illuminant 項(xiàng)目一起使用,但是其思路可以參考。
代碼生成無(wú)非就是找出重復(fù)代碼的規(guī)律,將其中變化的部分定義出來(lái),然后通過(guò)模板來(lái)生成不同的代碼。通過(guò)模板來(lái)生成代碼,跟拷貝相似代碼來(lái)修改相比,可以有效減少很多人為造成的混亂,比如拷貝過(guò)來(lái)后漏改,或者有些多余代碼未刪除等等。
到此這篇關(guān)于golang 標(biāo)準(zhǔn)庫(kù)template的代碼生成的文章就介紹到這了,更多相關(guān)golang 標(biāo)準(zhǔn)庫(kù)template內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go語(yǔ)言學(xué)習(xí)之時(shí)間函數(shù)使用詳解
這篇文章主要為大家詳細(xì)介紹了Go語(yǔ)言中時(shí)間函數(shù)的使用方法,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Go語(yǔ)言有一定的幫助,需要的可以參考一下2022-04-04用gin開發(fā)的golang項(xiàng)目三種開發(fā)模式方式
這篇文章主要介紹了用gin開發(fā)的golang項(xiàng)目三種開發(fā)模式方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01Go語(yǔ)言自定義包構(gòu)建自己的編程工具庫(kù)
Go 語(yǔ)言的強(qiáng)大不僅體現(xiàn)在其內(nèi)置功能上,還在于其支持自定義包,這為開發(fā)者提供了極大的靈活性和可擴(kuò)展性,本文將深入介紹如何創(chuàng)建、使用和管理自定義包,探索 Go 語(yǔ)言包的奧秘,打造屬于你的編程工具庫(kù)2023-11-11go語(yǔ)言編程之美自定義二進(jìn)制文件實(shí)用指南
這篇文章主要介紹了go語(yǔ)言編程之美自定義二進(jìn)制文件實(shí)用指南2023-12-12使用golang實(shí)現(xiàn)一個(gè)MapReduce的示例代碼
這篇文章主要給大家介紹了關(guān)于如何使用golang實(shí)現(xiàn)一個(gè)MapReduce,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-09-09Go語(yǔ)言對(duì)字符串進(jìn)行SHA1哈希運(yùn)算的方法
這篇文章主要介紹了Go語(yǔ)言對(duì)字符串進(jìn)行SHA1哈希運(yùn)算的方法,實(shí)例分析了Go語(yǔ)言針對(duì)字符串操作的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03