import React, { useState } from 'react'; import { useTranslation } from 'react-i18next'; import userService from '../api/services/userService'; import Trash from '../assets/trash.svg'; import CreateAPIKeyModal from '../modals/CreateAPIKeyModal'; import SaveAPIKeyModal from '../modals/SaveAPIKeyModal'; import ConfirmationModal from '../modals/ConfirmationModal'; import { APIKeyData } from './types'; import SkeletonLoader from '../components/SkeletonLoader'; export default function APIKeys() { const { t } = useTranslation(); const [isCreateModalOpen, setCreateModal] = React.useState(false); const [isSaveKeyModalOpen, setSaveKeyModal] = React.useState(false); const [newKey, setNewKey] = React.useState(''); const [apiKeys, setApiKeys] = React.useState([]); const [loading, setLoading] = useState(true); const [keyToDelete, setKeyToDelete] = useState<{ id: string; name: string; } | null>(null); const handleFetchKeys = async () => { setLoading(true); try { const response = await userService.getAPIKeys(); if (!response.ok) { throw new Error('Failed to fetch API Keys'); } const apiKeys = await response.json(); setApiKeys(apiKeys); } catch (error) { console.log(error); } finally { setLoading(false); } }; const handleDeleteKey = (id: string) => { userService .deleteAPIKey({ id }) .then((response) => { if (!response.ok) { throw new Error('Failed to delete API Key'); } return response.json(); }) .then((data) => { data.success === true && setApiKeys((previous) => previous.filter((elem) => elem.id !== id)); setKeyToDelete(null); }) .catch((error) => { console.error(error); }); }; const handleCreateKey = (payload: { name: string; source?: string; retriever?: string; prompt_id: string; chunks: string; }) => { userService .createAPIKey(payload) .then((response) => { if (!response.ok) { throw new Error('Failed to create API Key'); } return response.json(); }) .then((data) => { setApiKeys([...apiKeys, data]); setCreateModal(false); setNewKey(data.key); setSaveKeyModal(true); handleFetchKeys(); }) .catch((error) => { console.error(error); }); }; React.useEffect(() => { handleFetchKeys(); }, []); return (
{isCreateModalOpen && ( setCreateModal(false)} /> )} {isSaveKeyModalOpen && ( setSaveKeyModal(false)} /> )} {keyToDelete && ( setKeyToDelete(null)} submitLabel={t('modals.deleteConv.delete')} handleSubmit={() => handleDeleteKey(keyToDelete.id)} handleCancel={() => setKeyToDelete(null)} /> )}
{loading ? ( ) : (
{!apiKeys?.length && ( )} {Array.isArray(apiKeys) && apiKeys?.map((element, index) => ( ))}
{t('settings.apiKeys.name')} {t('settings.apiKeys.sourceDoc')} {t('settings.apiKeys.key')}
{t('settings.apiKeys.noData')}
{element.name} {element.source} {element.key} {`Delete setKeyToDelete({ id: element.id, name: element.name, }) } />
)}
); }