Browse Source

接口元数据增删改查、打标、资源申请编码实现

master
zmh 2 years ago
parent
commit
814c3d6358
  1. 4
      api/app/lib/controllers/latestMetadata/index.js
  2. 4
      web/client/src/sections/metadataAcquisition/containers/adapter.js
  3. 196
      web/client/src/sections/metadataManagement/components/metadataRestapiModal.js
  4. 1
      web/client/src/sections/metadataManagement/constants/index.js
  5. 234
      web/client/src/sections/metadataManagement/containers/restapisTable.js

4
api/app/lib/controllers/latestMetadata/index.js

@ -169,6 +169,8 @@ async function getMetadataFiles(ctx) {
const models = ctx.fs.dc.models; const models = ctx.fs.dc.models;
const { catalog, limit, offset, keywords, orderBy = 'updateAt', orderDirection = 'desc' } = ctx.query; const { catalog, limit, offset, keywords, orderBy = 'updateAt', orderDirection = 'desc' } = ctx.query;
const where = { catalog: catalog }; const where = { catalog: catalog };
//文件类型关键字查询时需匹配fileName不能为空。
//因存在编辑时将文件删除,但未重新上传直接点击取消的情况,此时文件已删除不可恢复,数据字段fileName更新为null
if (keywords) { if (keywords) {
where['$or'] = [{ name: { $iLike: `%${keywords}%` } }, { type: { $iLike: `%${keywords}%` }, fileName: { $not: null } }] where['$or'] = [{ name: { $iLike: `%${keywords}%` } }, { type: { $iLike: `%${keywords}%` }, fileName: { $not: null } }]
} }
@ -746,7 +748,7 @@ async function delMetadataRestapis(ctx) {
} else { } else {
let resourceConsumptionInfo = await models.ResourceConsumption.findOne({ let resourceConsumptionInfo = await models.ResourceConsumption.findOne({
where: { where: {
resourceName: metadataFileInfo.name, resourceName: metadataRestapiInfo.name,
resourceType: '接口' resourceType: '接口'
} }
}); });

4
web/client/src/sections/metadataAcquisition/containers/adapter.js

@ -7,7 +7,7 @@ import moment from 'moment';
import { RELATION_DATABASE_TOOL_CONFIG } from '../constants/adapter'; import { RELATION_DATABASE_TOOL_CONFIG } from '../constants/adapter';
import { useFsRequest, ApiTable } from '$utils'; import { useFsRequest, ApiTable } from '$utils';
const LatestMetadata = (props) => { const Adapter = (props) => {
const { history, actions, dispatch, adapters } = props; const { history, actions, dispatch, adapters } = props;
const [isModalOpen, setIsModalOpen] = useState(false); const [isModalOpen, setIsModalOpen] = useState(false);
const [refreshTree, setRefreshTree] = useState(1); const [refreshTree, setRefreshTree] = useState(1);
@ -114,4 +114,4 @@ function mapStateToProps(state) {
dataSources: datasources?.data || {}, dataSources: datasources?.data || {},
}; };
} }
export default connect(mapStateToProps)(LatestMetadata) export default connect(mapStateToProps)(Adapter)

196
web/client/src/sections/metadataManagement/components/metadataRestapiModal.js

@ -0,0 +1,196 @@
import React, { useEffect, useState } from 'react';
import { Modal, Input, Form, Select, InputNumber, Tooltip, Switch } from 'antd';
import { RestapiMethods } from '../constants/index';
const { TextArea } = Input;
const MetadataRestapiModal = (props) => {
const { onConfirm, onCancel, editData, metadataModels } = props;
const [form] = Form.useForm();
const [bodyParamRequired, setBodyParamRequired] = useState(false);
const [returnRequired, setReturnRequired] = useState(false);
useEffect(() => {
// form.setFieldValue('enabled', editData.record?.enabled || false);
}, []);
const handleOk = () => {
form.validateFields().then(values => {
if (onConfirm) {
let dataSave = JSON.parse(JSON.stringify(values));
dataSave.attributesParam = {};
metadataModels.map(m => {
dataSave.attributesParam[m.attributeCode] = values[m.attributeCode];
delete dataSave[m.attributeCode];
})
onConfirm(dataSave);
}
})
}
const isObjectString = (value) => {
if (typeof value !== "string") {
return false;
}
try {
JSON.parse(value);
return true;
} catch (e) {
return false;
}
}
const validatorNull = (rule, value, getFieldValue, validateFields, label) => {
if (!value || !value.trim().length) {
return Promise.reject(new Error(`${label}不可空字符串`));
}
return Promise.resolve();
}
const renderModelItems = () => {
const items = metadataModels.filter(mm => mm.modelType === '接口').map(m => {
if (m.control === '文本框') {
const rules = [{ required: !m.nullable, message: '' }]
if (!m.nullable) {
rules.push(({ getFieldValue, validateFields }) => ({
validator(_, value) { return validatorNull(_, value, getFieldValue, validateFields, m.attributeName) }
}))
rules.push({ max: m.length, message: `${m.attributeName}不超过${m.length}个字符` })
}
return <Form.Item
label={m.attributeName.length > 10 ? <Tooltip title={m.attributeName}>
{m.attributeName.substring(0, 10) + '...'}
</Tooltip> : m.attributeName}
name={m.attributeCode}
key={m.attributeCode}
rules={rules}>
<Input style={{ width: '90%' }} placeholder={`请输入${m.attributeName}`} />
</Form.Item>
} else if (m.control === '数字输入框') {
const rules = [{ required: !m.nullable, message: `${m.attributeName}不可空` }]
let maxValue = '';
let length = m.length;
if (length) {
while (length > 0) {
maxValue += '9'
length--;
}
}
return <Form.Item
label={m.attributeName.length > 10 ? <Tooltip title={m.attributeName}>
{m.attributeName.substring(0, 10) + '...'}
</Tooltip> : m.attributeName}
name={m.attributeCode}
key={m.attributeCode}
rules={rules}>
<InputNumber min={0} max={maxValue ? parseInt(maxValue) : 0} precision={0} style={{ width: '90%' }} placeholder={`请输入${m.attributeName}`} />
</Form.Item>
} else {
return <Form.Item
label={m.attributeName.length > 10 ? <Tooltip title={m.attributeName}>
{m.attributeName.substring(0, 10) + '...'}
</Tooltip> : m.attributeName}
name={m.attributeCode}
key={m.attributeCode}
rules={[{ required: !m.nullable, message: `${m.attributeName}不可空` }]}>
<Select
placeholder={`请选择${m.attributeName}`}
style={{ width: '90%' }}
showSearch
optionFilterProp='children'
getPopupContainer={triggerNode => triggerNode.parentNode}
filterOption={(input, option) => option.props.children
.toLowerCase().indexOf(input.toLowerCase()) >= 0}
>
<Select.Option value={'是'} key={'是'}></Select.Option>
<Select.Option value={'否'} key={'否'}></Select.Option>
</Select>
</Form.Item >
}
})
return items;
}
return (
<Modal title={editData.title} open={true} destroyOnClose
okText='确定' width={800}
onOk={() => handleOk(null)}
onCancel={onCancel}>
<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} initialValues={editData.record || {}}>
<Form.Item
label='接口名称'
name='name'
key='name'
rules={[{ required: true, message: '' }, { max: 255, message: `接口名称不超过255个字符` },
({ getFieldValue, validateFields }) => ({
validator(_, value) { return validatorNull(_, value, getFieldValue, validateFields, '接口名称') }
})]}>
<Input style={{ width: '90%' }} placeholder={`请输入接口名称`} />
</Form.Item>
<Form.Item
label='接口路由'
name='url'
key='url'
rules={[{ required: true, message: '' }, { max: 255, message: `接口路由不超过255个字符` },
({ getFieldValue, validateFields }) => ({
validator(_, value) { return validatorNull(_, value, getFieldValue, validateFields, '接口路由') }
})]}>
<Input style={{ width: '90%' }} placeholder={`请输入接口路由`} />
</Form.Item>
<Form.Item
label="接口类型"
name='method'
key='method'
rules={[{ required: true, message: '请选择接口类型' }]}>
<Select
placeholder='请选择接口类型'
style={{ width: '90%' }}
showSearch
optionFilterProp='children'
getPopupContainer={triggerNode => triggerNode.parentNode}
filterOption={(input, option) => option.props.children
.toLowerCase().indexOf(input.toLowerCase()) >= 0}
onChange={value => {
if (value === 'post' || value === 'put') {
setBodyParamRequired(true)
setReturnRequired(false)
}
if (value === 'get') {
setBodyParamRequired(false)
setReturnRequired(true)
}
if (value === 'delete') {
setBodyParamRequired(false)
setReturnRequired(false)
}
}}
>
{RestapiMethods.map(m => <Select.Option value={m} key={m}>{m}</Select.Option>)}
</Select>
</Form.Item>
<Form.Item
label='传参'
name='queryParam'
key='queryParam'
rules={[{ max: 255, message: `传参不超过255个字符` }]}>
<TextArea rows={3} style={{ width: '90%' }} />
</Form.Item>
<Form.Item
label='请求实体'
name='bodyParam'
key='bodyParam'
rules={[{ required: bodyParamRequired }]}>
<TextArea rows={3} style={{ width: '90%' }} placeholder={`请输入请求实体`} />
</Form.Item>
<Form.Item
label='返回值'
name='return'
key='return'
rules={[{ required: returnRequired }]}>
<TextArea rows={3} style={{ width: '90%' }} placeholder={`请输入返回值`} />
</Form.Item>
<Form.Item
label='状态'
name='enabled'
key='enabled'
valuePropName='checked'>
<Switch checkedChildren="启用" unCheckedChildren="禁用" />
</Form.Item>
{renderModelItems()}
</Form>
</Modal >
)
}
export default MetadataRestapiModal;

1
web/client/src/sections/metadataManagement/constants/index.js

@ -1,6 +1,7 @@
'use strict'; 'use strict';
import React from 'react'; import React from 'react';
export const ModelTypes = ['目录', '库', '视图', '表', '字段', '索引', '外键', '主键', '唯一约束']; export const ModelTypes = ['目录', '库', '视图', '表', '字段', '索引', '外键', '主键', '唯一约束'];
export const RestapiMethods = ['get', 'post', 'put', 'delete'];
export const ConfigurableTypes = { export const ConfigurableTypes = {
'目录': ['库'], '目录': ['库'],
'库': ['视图', '表'], '库': ['视图', '表'],

234
web/client/src/sections/metadataManagement/containers/restapisTable.js

@ -1,41 +1,107 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { Spin, Table, Popconfirm } from 'antd'; import { Spin, Table, Popconfirm, Button, Input } from 'antd';
import moment from 'moment'; import { ButtonGroup } from '$components';
import MetadataRestapiModal from '../components/metadataRestapiModal';
import MetadataTagModal from '../components/metadataTagModal';
import MetadataResourceModal from '../components/metadataResourceModal';
const RestapisTable = (props) => { const RestapisTable = (props) => {
const { user, dispatch, actions, clientHeight, resourceCatalogId, isRequesting } = props; const { user, dispatch, actions, clientHeight, resourceCatalogId, resourceCatalogKey,
isRequesting, metadataModels, tagList, metadataResourceApplications } = props;
const { metadataManagement } = actions; const { metadataManagement } = actions;
const [resourceCatalogData, setResourceCatalogData] = useState([]); const [tableData, setTableData] = useState([]);
const [limit, setLimit] = useState(10) const [tableDataCount, setTableDataCount] = useState(0);//Table数据
const [offset, setOffset] = useState(0) const [keywords, setKeywords] = useState('');
const [limit, setLimit] = useState(10);
const [currentPage, setCurrentPage] = useState(1);
const [modalVisible, setModalVisible] = useState(false);
const [editData, setEditData] = useState({});
const [tagModalVisible, setTagModalVisible] = useState(false);
const [editTagData, setEditTagData] = useState({});
const [resourceModalVisible, setResourceModalVisible] = useState(false);
const [editResourceData, setEditResourceData] = useState({});
useEffect(() => { useEffect(() => {
initData(); dispatch(metadataManagement.getTagList());
initData({ limit, offset: currentPage - 1 });
}, []); }, []);
const initData = () => { const initData = (query = {}) => {
dispatch(metadataManagement.getMetadataRestapis({ catalog: resourceCatalogId, limit, offset })).then(res => { dispatch(metadataManagement.getMetadataRestapis({ catalog: resourceCatalogId, keywords, ...query })).then(res => {
const { data } = res.payload;
if (res.success) { if (res.success) {
setTableData(res.payload.data.rows);
setTableDataCount(res.payload.data.count);
let resourceNames = [];
res.payload.data.rows.map(r => {
resourceNames.push(r.name);
})
if (resourceNames.length)
dispatch(metadataManagement.getMetadataResourceApplications({ resourceNames: resourceNames.join(','), type: '接口' }))
}
})
}
const onEdit = (record) => {
dispatch(metadataManagement.getMetadataModels({ modelTypes: '接口' })).then(res => {
if (res.success) {
setEditData({ title: '修改接口元数据', record: { ...record, ...record.attributesParam } });
setModalVisible(true);
}
})
}
const confirmDelete = (id) => {
dispatch(metadataManagement.delMetadataRestapis(id)).then(res => {
if (res.success) {
onSearch(); setModalVisible(false);
}
});
}
const marking = (id) => {
dispatch(metadataManagement.getTagMetadata(id, 'restapi')).then(res => {
if (res.success) {
const obj = { tagSet: [], tags: [], id: id };
if (res.payload.data.length) {
const tagSetIds = res.payload.data.map(d => d.tagSet)
obj.tagSet = [...new Set(tagSetIds)];
obj.tags = res.payload.data.map(d => d.id);
}
setEditTagData({ record: obj });
setTagModalVisible(true);
} }
}) })
} }
const onEdit = (record) => { } const onConfirmTag = (values) => {
const confirmDelete = (id) => { } dispatch(metadataManagement.postTagMetadata({ restapi: editTagData.record.id, ...values })).then(res => {
const marking = (id) => { } if (res.success) {
const applyResources = (id) => { } onSearch(); setTagModalVisible(false);
}
});
}
const applyResources = (record) => {
setEditResourceData({ record: { resourceName: record.name, applyBy: user.id, applyByName: user.name, resourceType: '接口' } });
setResourceModalVisible(true);
}
const onConfirmResource = (values) => {
dispatch(metadataManagement.postMetadataResourceApplications(values)).then(res => {
if (res.success) {
onSearch(); setResourceModalVisible(false);
}
});
}
const columns = [{ const columns = [{
title: '接口名称', title: '接口名称',
dataIndex: 'name', dataIndex: 'name',
key: 'name', key: 'name',
width: '20%' ellipsis: true,
width: '23%'
}, { }, {
title: '接口路由', title: '接口路由',
dataIndex: 'url', dataIndex: 'url',
key: 'url', key: 'url',
width: '20%' ellipsis: true,
width: '23%'
}, { }, {
title: '接口类型', title: '接口类型',
dataIndex: 'method', dataIndex: 'method',
@ -45,58 +111,152 @@ const RestapisTable = (props) => {
title: '传参', title: '传参',
dataIndex: 'queryParam', dataIndex: 'queryParam',
key: 'queryParam', key: 'queryParam',
ellipsis: true,
width: '20%' width: '20%'
}, { }, {
title: '返回值', title: '返回值',
dataIndex: 'return', dataIndex: 'return',
key: 'return', key: 'return',
width: '20%' ellipsis: true,
width: '23%'
}, { }, {
title: '标签', title: '标签',
dataIndex: 'tags', dataIndex: 'tags',
key: 'tags', key: 'tags',
width: '20%' width: '23%',
ellipsis: true,
render: (text, record, index) => {
let tagName = record.tagRestapis.map(tagSet => tagSet.tag.name);
return tagName.join(',');
}
}, { }, {
title: '状态', title: '状态',
dataIndex: 'enabled', dataIndex: 'enabled',
key: 'enabled', key: 'enabled',
width: '10%' width: '10%',
render: (text) => <span>{text ? '启用' : '禁用'}</span>
}, { }, {
title: '操作', title: '操作',
dataIndex: 'action', dataIndex: 'action',
width: '20%', width: '8%',
render: (text, record) => { render: (text, record) => {
return <div> let resourceApplicationsRecords = metadataResourceApplications.filter(ra =>
<a onClick={() => onEdit(record)}>编辑</a> ra.applyBy == user.id && ra.resourceName === record.name);
&nbsp;&nbsp; return <ButtonGroup>
<a style={{ marginLeft: 10 }} onClick={() => onEdit(record)}>编辑</a>
<Popconfirm <Popconfirm
title="是否确认删除该元数据?若确认删除则关联的数据将一并删除!" title="是否确认删除该元数据?"
onConfirm={() => confirmDelete(record.id)} onConfirm={() => confirmDelete(record.id)}
> <a>删除</a></Popconfirm> > <a style={{ marginLeft: 10 }}>删除</a></Popconfirm>
&nbsp;&nbsp; <a style={{ marginLeft: 10 }} onClick={() => marking(record.id)}>打标</a>
<a onClick={() => marking(record.id)}>打标</a> {resourceApplicationsRecords.length === 0 ?
&nbsp;&nbsp; <a style={{ marginLeft: 10 }} onClick={() => applyResources(record)}>申请资源</a> :
<a onClick={() => applyResources(record.id)}>申请资源</a> <span style={{ marginLeft: 10, color: "#c0c0c0" }} title='已存在资源申请'>申请资源</span>}
</div> </ButtonGroup>
} }
}]; }];
const onSearch = () => {
setCurrentPage(1);
initData({ limit, offset: 0 });
}
//新建、修改
const onConfirm = (values) => {
let obj = {}
if (editData.add) {
obj = { createBy: user.id, catalog: resourceCatalogId, catalogKey: resourceCatalogKey, ...values }
dispatch(metadataManagement.postMetadataRestapis(obj)).then(() => {
onSearch(); setModalVisible(false);
});
} else {
obj = { catalog: resourceCatalogId, catalogKey: resourceCatalogKey, ...values }
dispatch(metadataManagement.putMetadataRestapis(editData.record.id, obj)).then(res => {
if (res.success) {
onSearch(); setModalVisible(false);
}
});
}
}
return <Spin spinning={isRequesting}> return <Spin spinning={isRequesting}>
<Table scroll={{ y: clientHeight - 320 }} <div style={{ marginBottom: 16 }}>
rowKey='restapisId' <Button type='primary' onClick={() => {
dispatch(metadataManagement.getMetadataModels({ modelTypes: '接口' })).then(res => {
if (res.success) {
setEditData({ add: true, title: '新建接口元数据', record: {} });
setModalVisible(true);
}
})
}}>新建</Button>
<Button type='primary' style={{ marginLeft: 16, float: 'right' }} onClick={onSearch}>查询</Button>
<Input style={{ width: 220, float: 'right' }} placeholder="输入名称"
allowClear onPressEnter={onSearch} onChange={e => setKeywords(e.target.value || '')} />
</div >
<Table
scroll={{ y: clientHeight - 320 }}
rowKey='id'
columns={columns} columns={columns}
dataSource={[]}> dataSource={tableData}
pagination={{
current: currentPage,
pageSize: limit,
total: tableDataCount,
showSizeChanger: true,
// showQuickJumper: true,
showTotal: (total) => { return <span style={{ fontSize: 15 }}>{`${Math.ceil(total / limit)}页,${total}`}</span> },
onShowSizeChange: (currentPage, pageSize) => {
setCurrentPage(currentPage);
setLimit(pageSize);
},
onChange: (page, pageSize) => {
setCurrentPage(page);
setLimit(pageSize);
let queryParams = {
offset: page - 1,
limit: pageSize
};
initData(queryParams);
}
}}
>
</Table> </Table>
</Spin> {
modalVisible ?
<MetadataRestapiModal
metadataModels={metadataModels.filter(m => m.modelType === '接口')}
editData={editData}
onCancel={() => {
setModalVisible(false);
}}
onConfirm={onConfirm} /> : ''
}
{
tagModalVisible ?
<MetadataTagModal
tagList={tagList}
editData={editTagData}
onCancel={() => setTagModalVisible(false)}
onConfirm={onConfirmTag} /> : ''
}
{
resourceModalVisible ?
<MetadataResourceModal
editData={editResourceData}
onCancel={() => setResourceModalVisible(false)}
onConfirm={onConfirmResource} /> : ''
}
</Spin >
} }
function mapStateToProps(state) { function mapStateToProps(state) {
const { global, auth, metadataRestapis } = state; const { global, auth, metadataRestapis, metadataModels, tagList, tagMetadata, metadataResourceApplications } = state;
return { return {
user: auth.user, user: auth.user,
actions: global.actions, actions: global.actions,
clientHeight: global.clientHeight, clientHeight: global.clientHeight,
isRequesting: metadataRestapis.isRequesting isRequesting: metadataRestapis.isRequesting || metadataModels.isRequesting || tagList.isRequesting
|| tagMetadata.isRequesting || metadataResourceApplications.isRequesting,
metadataModels: metadataModels.data,
tagList: tagList.data || [],
metadataResourceApplications: metadataResourceApplications.data || []
}; };
} }
export default connect(mapStateToProps)(RestapisTable) export default connect(mapStateToProps)(RestapisTable)
Loading…
Cancel
Save