feat: code generator

This commit is contained in:
dap 2024-09-23 22:11:31 +08:00
parent 07e9483c91
commit 054fbf72cd
9 changed files with 478 additions and 33 deletions

View File

@ -0,0 +1,102 @@
import type { GenInfo } from './model';
import type { ID, IDS } from '#/api/common';
import { ContentTypeEnum } from '#/api/helper';
import { requestClient } from '#/api/request';
enum Api {
batchGenCode = '/tool/gen/batchGenCode',
columnList = '/tool/gen/column',
dataSourceNames = '/tool/gen/getDataNames',
download = '/tool/gen/download',
genCode = '/tool/gen/genCode',
generatedList = '/tool/gen/list',
importTable = '/tool/gen/importTable',
preview = '/tool/gen/preview',
readyToGenList = '/tool/gen/db/list',
root = '/tool/gen',
syncDb = '/tool/gen/synchDb',
}
// 查询代码生成列表
export function generatedList(params: any) {
return requestClient.get(Api.generatedList, { params });
}
// 修改代码生成业务
export function genInfo(tableId: ID) {
return requestClient.get<GenInfo>(`${Api.root}/${tableId}`);
}
// 查询数据库列表
export function readyToGenList(params: any) {
return requestClient.get(Api.readyToGenList, { params });
}
// 查询数据表字段列表
export function columnList(tableId: ID) {
return requestClient.get(`${Api.columnList}/${tableId}`);
}
/**
*
* @param tables table名称数组 sys_a, sys_b
* @param dataName
* @returns ret
*/
export function importTable(tables: string | string[], dataName: string) {
return requestClient.postWithMsg(
Api.importTable,
{ dataName, tables },
{
headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED },
},
);
}
// 修改保存代码生成业务
export function editSave(data: any) {
return requestClient.putWithMsg(Api.root, data);
}
// 删除代码生成
export function genRemove(tableIds: IDS) {
return requestClient.deleteWithMsg(`${Api.root}/${tableIds}`);
}
// 预览代码
export function previewCode(tableId: ID) {
return requestClient.get<{ [key: string]: string }>(
`${Api.preview}/${tableId}`,
);
}
// 生成代码(下载方式)
export function genDownload(tableId: ID) {
return requestClient.get<Blob>(`${Api.download}/${tableId}`);
}
// 生成代码(自定义路径)
export function genDownloadWithPath(tableId: ID) {
return requestClient.get(`${Api.download}/${tableId}`);
}
// 同步数据库
export function syncDb(tableId: ID) {
return requestClient.get(`${Api.syncDb}/${tableId}`, {
successMessageMode: 'message',
});
}
// 批量生成代码
export function batchGenCode(tableIdStr: ID | IDS) {
return requestClient.get<Blob>(Api.batchGenCode, {
isTransformResponse: false,
params: { tableIdStr },
responseType: 'blob',
});
}
// 查询数据源名称列表
export function getDataSourceNames() {
return requestClient.get<string[]>(Api.dataSourceNames);
}

View File

@ -0,0 +1,185 @@
export interface Column {
createDept?: any;
createBy?: any;
createTime?: any;
updateBy?: any;
updateTime?: any;
columnId: string;
tableId: string;
columnName: string;
columnComment: string;
columnType: string;
javaType: string;
javaField: string;
isPk: string;
isIncrement: string;
isRequired: string;
isInsert?: any;
isEdit: string;
isList: string;
isQuery?: any;
queryType: string;
htmlType: string;
dictType: string;
sort: number;
list: boolean;
required: boolean;
pk: boolean;
insert: boolean;
edit: boolean;
usableColumn: boolean;
superColumn: boolean;
increment: boolean;
query: boolean;
capJavaField: string;
}
export interface Table {
createDept?: any;
createBy?: any;
createTime?: any;
updateBy?: any;
updateTime?: any;
tableId: string;
dataName: string;
tableName: string;
tableComment: string;
subTableName?: any;
subTableFkName?: any;
className: string;
tplCategory: string;
packageName: string;
moduleName: string;
businessName: string;
functionName: string;
functionAuthor: string;
genType?: any;
genPath?: any;
pkColumn?: any;
columns: Column[];
options?: any;
remark?: any;
treeCode?: any;
treeParentCode?: any;
treeName?: any;
menuIds?: any;
parentMenuId?: any;
parentMenuName?: any;
tree: boolean;
crud: boolean;
}
export interface Row {
createDept: number;
createBy: number;
createTime: string;
updateBy: number;
updateTime: string;
columnId: string;
tableId: string;
columnName: string;
columnComment: string;
columnType: string;
javaType: string;
javaField: string;
isPk: string;
isIncrement: string;
isRequired: string;
isInsert?: any;
isEdit: string;
isList: string;
isQuery?: any;
queryType: string;
htmlType: string;
dictType: string;
sort: number;
list: boolean;
required: boolean;
pk: boolean;
insert: boolean;
edit: boolean;
usableColumn: boolean;
superColumn: boolean;
increment: boolean;
query: boolean;
capJavaField: string;
}
export interface Column {
createDept?: any;
createBy?: any;
createTime?: any;
updateBy?: any;
updateTime?: any;
columnId: string;
tableId: string;
columnName: string;
columnComment: string;
columnType: string;
javaType: string;
javaField: string;
isPk: string;
isIncrement: string;
isRequired: string;
isInsert?: any;
isEdit: string;
isList: string;
isQuery?: any;
queryType: string;
htmlType: string;
dictType: string;
sort: number;
list: boolean;
required: boolean;
pk: boolean;
insert: boolean;
edit: boolean;
usableColumn: boolean;
superColumn: boolean;
increment: boolean;
query: boolean;
capJavaField: string;
}
export interface Info {
createDept?: any;
createBy?: any;
createTime?: any;
updateBy?: any;
updateTime?: any;
tableId: string;
dataName: string;
tableName: string;
tableComment: string;
subTableName?: any;
subTableFkName?: any;
className: string;
tplCategory: string;
packageName: string;
moduleName: string;
businessName: string;
functionName: string;
functionAuthor: string;
genType: string;
genPath: string;
pkColumn?: any;
columns: Column[];
options?: any;
remark?: any;
treeCode?: any;
treeParentCode?: any;
treeName?: any;
menuIds?: any;
parentMenuId?: any;
parentMenuName?: any;
tree: boolean;
crud: boolean;
// 树表需要添加此属性
params?: any;
}
export interface GenInfo {
tables: Table[];
rows: Row[];
info: Info;
}

View File

@ -50,7 +50,8 @@
"sync": "Sync",
"refresh": "Refresh",
"generate": "Generate",
"downloadLoading": "Downloading... Please wait."
"downloadLoading": "Downloading... Please wait.",
"preview": "Preview"
}
}
}

View File

@ -50,7 +50,8 @@
"sync": "同步",
"refresh": "刷新",
"generate": "生成",
"downloadLoading": "下载中, 请稍后..."
"downloadLoading": "下载中, 请稍后...",
"preview": "预览"
}
}
}

View File

@ -57,6 +57,30 @@ const profileRoute: RouteRecordStringComponent[] = [
},
],
},
{
component: 'BasicLayout',
meta: {
hideChildrenInMenu: true,
hideInMenu: true,
title: '修改生成配置',
},
name: 'GenConfig',
path: '/',
redirect: '/code-gen/edit',
children: [
{
component: '/tool/gen/edit-gen',
meta: {
activePath: '/tool/gen',
icon: 'mingcute:profile-line',
keepAlive: true,
title: '生成配置',
},
name: 'GenConfigIndex',
path: '/code-gen/edit/:tableId',
},
],
},
];
/**

View File

@ -1,4 +1,5 @@
<script setup lang="ts">
import type { Recordable } from '@vben/types';
import type { Key } from 'ant-design-vue/es/vc-tree/interface';
import { ref } from 'vue';
@ -10,9 +11,9 @@ import {
} from '@vben/common-ui';
import { Icon } from '@vben/icons';
import { Tree } from 'ant-design-vue';
import { Skeleton, Tree } from 'ant-design-vue';
import { data } from './preview.json';
import { previewCode } from '#/api/tool/gen';
interface TreeNode {
children: TreeNode[];
@ -26,14 +27,24 @@ const treeData = ref<TreeNode[]>([]);
const modalTitle = ref('代码预览');
/** 代码内容 */
const codeContent = ref('点击左侧树节点查看代码');
/** code */
const currentCodeData = ref<null | Recordable<any>>(null);
const [BasicModal] = useVbenModal({
onOpenChange(isOpen) {
const [BasicModal, modalApi] = useVbenModal({
async onOpenChange(isOpen) {
if (!isOpen) {
handleClose();
return null;
}
modalApi.modalLoading(true);
const { tableId } = modalApi.getData() as { tableId: string };
const data = await previewCode(tableId);
currentCodeData.value = data;
const tree = convertToTree(Object.keys(data));
treeData.value = tree;
modalApi.modalLoading(false);
},
});
@ -116,7 +127,11 @@ function changeLanguageType(filename: string) {
function handleSelect(selectedKeys: Key[]) {
const [currentFile = ''] = selectedKeys as string[];
const currentCode = data[currentFile as keyof typeof data];
if (!currentCodeData.value) {
return;
}
const currentCode =
currentCodeData.value[currentFile as keyof typeof currentCodeData.value];
if (currentCode) {
// type
changeLanguageType(currentFile);
@ -126,6 +141,13 @@ function handleSelect(selectedKeys: Key[]) {
modalTitle.value = `代码预览: ${currentFile.replace('.vm', '')}`;
}
}
function handleClose() {
currentCodeData.value = null;
codeContent.value = '点击左侧树节点查看代码';
modalTitle.value = '代码预览';
language.value = 'html';
}
</script>
<template>
@ -135,7 +157,7 @@ function handleSelect(selectedKeys: Key[]) {
:fullscreen-button="false"
:title="modalTitle"
>
<div class="flex gap-[8px]">
<div v-if="currentCodeData" class="flex gap-[8px]">
<Tree
v-if="treeData.length > 0"
:tree-data="treeData"
@ -157,6 +179,7 @@ function handleSelect(selectedKeys: Key[]) {
readonly
/>
</div>
<Skeleton v-if="!currentCodeData" active />
</BasicModal>
</template>

View File

@ -0,0 +1,26 @@
<script setup lang="ts">
import { onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { Page } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { genInfo } from '#/api/tool/gen';
const { setTabTitle } = useTabs();
const routes = useRoute();
const tableId = routes.params.tableId as string;
onMounted(async () => {
const resp = await genInfo(tableId);
console.log(resp);
setTabTitle(`生成配置: ${resp.info.tableName}`);
});
</script>
<template>
<Page>
<div>修改代码生成</div>
{{ tableId }}
</Page>
</template>

View File

@ -1,20 +1,126 @@
<script setup lang="ts">
import type { Recordable } from '@vben/types';
import type { ColumnsType } from 'ant-design-vue/es/table';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { Page, useVbenModal } from '@vben/common-ui';
import { message, Popconfirm, Table } from 'ant-design-vue';
import { batchGenCode, generatedList, genRemove, syncDb } from '#/api/tool/gen';
import { downloadByData } from '#/utils/file/download';
import codePreviewModal from './code-preview-modal.vue';
const [CodePreviewModal, previewModalApi] = useVbenModal({
connectedComponent: codePreviewModal,
});
function handlePreview() {
const columns: ColumnsType = [
{
dataIndex: 'tableName',
title: '表名称',
},
{
dataIndex: 'tableComment',
title: '表描述',
},
{
dataIndex: 'className',
title: '实体类',
},
{
dataIndex: 'createTime',
title: '创建时间',
},
{
dataIndex: 'updateTime',
title: '更新时间',
},
{
align: 'center',
dataIndex: 'action',
title: '操作',
},
];
const dataSource = ref([]);
onMounted(async () => {
const resp = await generatedList({});
dataSource.value = resp.rows;
});
function handlePreview(record: Recordable<any>) {
previewModalApi.setData({ tableId: record.tableId });
previewModalApi.open();
}
const router = useRouter();
function handleEdit(record: Recordable<any>) {
router.push(`/code-gen/edit/${record.tableId}`);
}
async function handleSync(record: Recordable<any>) {
await syncDb(record.tableId);
// reload
}
async function handleDownload(record: Recordable<any>) {
const hideLoading = message.loading('下载中...');
try {
const blob = await batchGenCode(record.tableId);
const filename = `代码生成_${record.tableName}_${new Date().toLocaleString()}.zip`;
downloadByData(blob, filename);
} catch (error) {
console.error(error);
} finally {
hideLoading();
}
}
async function handleDelete(record: Recordable<any>) {
await genRemove(record.tableId);
// reload
}
</script>
<template>
<Page>
<a-button @click="handlePreview">代码预览</a-button>
<Table :columns="columns" :data-source="dataSource" e="middle">
<template #bodyCell="{ record, column }">
<template v-if="column.dataIndex === 'action'">
<a-button size="small" type="link" @click="handlePreview(record)">
{{ $t('pages.common.preview') }}
</a-button>
<a-button size="small" type="link" @click="handleEdit(record)">
{{ $t('pages.common.edit') }}
</a-button>
<Popconfirm
:title="`确认同步[${record.tableName}]?`"
placement="left"
@confirm="handleSync(record)"
>
<a-button size="small" type="link">
{{ $t('pages.common.sync') }}
</a-button>
</Popconfirm>
<a-button size="small" type="link" @click="handleDownload(record)">
生成代码
</a-button>
<Popconfirm
:title="`确认删除[${record.tableName}]?`"
placement="left"
@confirm="handleDelete(record)"
>
<a-button danger size="small" type="link">
{{ $t('pages.common.delete') }}
</a-button>
</Popconfirm>
</template>
</template>
</Table>
<CodePreviewModal />
</Page>
</template>

File diff suppressed because one or more lines are too long