import { type FC, useState, useRef, useEffect } from 'react'; import clsx from 'clsx'; import { useTranslation } from 'react-i18next'; import { Button, Space, App, Statistic, Row, Col } from 'antd'; import copy from 'copy-to-clipboard' import Card from './components/Card'; import type { Application } from '@/views/ApplicationManagement/types' import type { ApiKeyModalRef, ApiKeyConfigModalRef } from './types' import type { ApiKey } from '@/views/ApiKeyManagement/types' import ApiKeyModal from './components/ApiKeyModal'; import ApiKeyConfigModal from './components/ApiKeyConfigModal'; import Tag from '@/components/Tag' import { getApiKeyList, getApiKeyStats, deleteApiKey } from '@/api/apiKey'; import { maskApiKeys } from '@/utils/apiKeyReplacer' const Api: FC<{ application: Application | null }> = ({ application }) => { const { t } = useTranslation(); const activeMethods = ['GET']; const { message, modal } = App.useApp() const copyContent = window.location.origin + '/v1/chat' const apiKeyModalRef = useRef(null); const apiKeyConfigModalRef = useRef(null); const [apiKeyList, setApiKeyList] = useState([]) const handleCopy = (content: string) => { copy(content) message.success(t('common.copySuccess')) } useEffect(() => { getApiList() }, []) const getApiList = () => { if (!application) { return } setApiKeyList([]) getApiKeyList({ type: application.type, is_active: true, resource_id: application.id, page: 1, pagesize: 10, }).then(res => { const response = res as { items: ApiKey[] } const list = response.items ?? [] getAllStats([...list]) }) } const getAllStats = (list: ApiKey[]) => { const allList: ApiKey[] = [] list.forEach(async item => { await getApiKeyStats(item.id) .then(res => { const response = res as { requests_today: number; total_requests: number; quota_limit: number; quota_used: number; } allList.push({ ...item, ...response, }) setApiKeyList(prev => [...prev, { ...item, ...response, }]) }) }) } const handleAdd = () => { apiKeyModalRef.current?.handleOpen() } const handleEdit = (vo: ApiKey) => { apiKeyConfigModalRef.current?.handleOpen(vo) } const handleDelete = (vo: ApiKey) => { modal.confirm({ title: t('common.confirmDeleteDesc', { name: vo.name }), content: t('application.apiKeyDeleteContent'), okText: t('common.delete'), okType: 'danger', onOk: () => { deleteApiKey(vo.id) .then(() => { getApiList(); message.success(t('common.deleteSuccess')) }) } }) } // 计算total_requests总数 const totalRequests = apiKeyList.reduce((total, item) => total + item.total_requests, 0); return (
{t('application.endpointConfigurationSubTitle')}
{['GET', 'POST', 'PUT', 'DELETE'].map((method) => (
{method}
))}
{copyContent}
+ {t('application.addApiKey')} } >
{t('application.apiKeySubTitle')}
{/* 总览数据 */} {/* API Key 列表 */} {apiKeyList.sort((a, b) => b.created_at - a.created_at).map(item => (
{item.name}
ID: {item.id}
handleEdit(item)} >
handleDelete(item)} >
{maskApiKeys(item.api_key)}
))}
); } export default Api;