use-document-request.ts
Overview
This file provides a suite of custom React hooks designed for managing documents within a knowledge base application. These hooks encapsulate API interactions related to document upload, fetching, status updates, execution, removal, renaming, parser configuration, metadata updates, and creation.
Leveraging React Query for data fetching and mutation, and integrating with a knowledge base service (kbService), the hooks provide:
Automated caching and invalidation of document-related queries.
Debounced search input handling.
Pagination and filtering logic linked with the router.
User feedback via success and error messages.
Status polling for documents currently "running".
These hooks abstract away the complexity of API communication and state management for document operations, allowing UI components to interact with documents in a declarative and reactive manner.
Detailed Explanations
Enum: DocumentApiAction
Defines constants representing different document-related API actions used as keys for React Query mutations and queries.
Key | Description |
|---|---|
Upload documents to knowledge base | |
| Retrieve list of documents |
Change document status | |
Execute documents by their IDs | |
| Delete documents |
| Rename a document |
| Change document parser configuration |
| Update document metadata |
| Get available document filters |
| Create a new document |
Hook: useUploadNextDocument
Uploads one or more files to the knowledge base linked to the current knowledge base ID.
Parameters
None directly; uses URL params to get knowledge base ID.
Returns
uploadDocument(files: File[]): Promise<ResponseType<IDocumentInfo[]>> - Function to trigger upload.
loading: boolean- Indicates upload in progress.data: ResponseType<IDocumentInfo[]> | undefined - Upload response data.
Implementation Details
Uses
useMutationfrom React Query.Appends files and kb_id to
FormData.Calls kbService.document_upload to send files.
On success or error code 500, invalidates the document list query to refresh data.
Usage Example
const { uploadDocument, loading } = useUploadNextDocument();
const handleFiles = (files: File[]) => {
uploadDocument(files).then(response => {
if (response?.code === 0) {
console.log('Upload successful');
}
});
};
Hook: useFetchDocumentList
Fetches and manages the paginated and filtered list of documents for the current knowledge base.
Returns
loading: boolean- Loading state during fetch.searchString: string- Current search input.documents: IDocumentInfo[]- List of fetched documents.pagination- Pagination state including total count.handleInputChange(event)- Handler for search input change.setPagination- Setter for pagination state.filterValue- Current filter criteria.handleFilterSubmit()- Function to apply filter.
Implementation Details
Uses
useQueryto fetch documents with keys depending on search, pagination, and filters.Implements polling every 5 seconds if any document is in "running" state (
doc.run === '1').Debounces search input with 500ms delay to reduce requests.
Sets documents in local state on each fetch.
Usage Example
const {
loading,
documents,
pagination,
handleInputChange,
setPagination,
filterValue,
handleFilterSubmit,
} = useFetchDocumentList();
return (
<input value={searchString} onChange={handleInputChange} />
// render documents list with pagination controls
);
Hook: useGetDocumentFilter
Retrieves available filters (e.g., by run status or file suffix) for documents in the current knowledge base.
Returns
filter: IDocumentInfoFilter- The filter options.onOpenChange(open: boolean): void- Function to trigger refetch on filter dropdown open.
Implementation Details
Uses
useQueryto fetch filter options.Refetches filters each time the dropdown is opened (tracked by
openstate counter).Debounced search string included in query key to sync filters with search.
Hook: useSetDocumentStatus
Updates the active/inactive status of one or more documents.
Returns
setDocumentStatus({ status, documentId })- Mutation function to update status.loading- Mutation loading state.data- Mutation response data.
Parameters
status: boolean- New status to set.documentId: string | string[]- One or multiple document IDs.
Implementation Details
Calls
kbService.document_change_status.Shows success message on success.
Invalidates document list query to refresh UI.
Hook: useRunDocument
Triggers the execution ("run") of documents by their IDs.
Returns
runDocumentByIds({ documentIds, run, shouldDelete })- Mutation function.loading- Mutation loading state.data- Mutation response code.
Parameters
documentIds: string[]- IDs of documents to run.run: number- Run mode/status.shouldDelete: boolean- Whether to delete documents after run.
Implementation Details
Calls
kbService.document_run.Invalidates document list queries before and after mutation.
Shows success message on success.
Hook: useRemoveDocument
Deletes one or multiple documents from the knowledge base.
Returns
removeDocument(documentIds)- Mutation function to remove documents.loading- Mutation loading state.data- Mutation response code.
Parameters
documentIds: string | string[]- Document IDs to delete.
Implementation Details
Calls
kbService.document_rm.Shows success message on success.
Invalidates document list query.
Hook: useSaveDocumentName
Renames a document.
Returns
saveName({ name, documentId })- Mutation function to rename.loading- Mutation loading state.data- Mutation response code.
Parameters
name: string- New document name.documentId: string- Target document ID.
Implementation Details
Calls
kbService.document_rename.Shows success message on success.
Invalidates document list query.
Hook: useSetDocumentParser
Sets the parser configuration for a document.
Returns
setDocumentParser({ parserId, documentId, parserConfig })- Mutation function.loading- Mutation loading state.data- Mutation response code.
Parameters
parserId: string- Parser identifier.documentId: string- Document identifier.parserConfig: IChangeParserConfigRequestBody- Parser configuration details.
Implementation Details
Calls
kbService.document_change_parser.Shows success message on success.
Invalidates document list query.
Hook: useSetDocumentMeta
Updates metadata for a document.
Returns
setDocumentMeta(params: IDocumentMetaRequestBody)- Mutation function.loading- Mutation loading state.data- Mutation response code.
Parameters
params: IDocumentMetaRequestBody- Includes metadata and document ID.
Implementation Details
Calls
kbService.setMeta.Shows success message on success.
Catches and shows error messages on failure.
Invalidates document list query.
Hook: useCreateDocument
Creates a new document under the current knowledge base.
Returns
createDocument(name: string)- Mutation function to create a document.loading- Mutation loading state.data- Mutation response code.
Parameters
name: string- Name of the new document.
Implementation Details
Calls
kbService.document_create.Conditionally invalidates or refreshes the document list based on current page.
Shows success message on success.
Important Implementation Details and Algorithms
React Query for Data Management: All fetch and mutation hooks use React Query to handle asynchronous data fetching, caching, and state updates efficiently.
Debounce Search Input: The
useDebouncehook prevents excessive API calls when the user types in the search input by delaying execution by 500ms.Polling for Running Documents: The document list query uses a 5-second refetch interval if any document is in a "running" state, allowing near real-time UI updates.
Query Invalidations: After mutations (upload, update, delete, etc.), related queries are invalidated to keep the UI in sync with the backend state.
Router Integration: Pagination and search parameters are linked with the router to enable URL-driven state and navigation.
User Notifications: Uses
messagecomponent to provide immediate feedback on successful or failed operations, improving UX.
File Interaction with Other Parts of the System
kbService: The primary service for all document-related API calls. This file depends heavily on it for backend communication.React Router (
useParams): Extracts knowledge base IDs directly from the URL.Localization (
i18n): Provides translated messages for user feedback.UI Components: This file exports hooks that are used by document-related UI components (e.g., document list, upload forms, filter bars).
Logic and Route Hooks: Imports custom hooks like
useGetPaginationWithRouter,useHandleSearchChange,useGetKnowledgeSearchParams, anduseSetPaginationParamsto manage state and routing logic seamlessly.React Query: Manages asynchronous data fetching and caching globally.
useHandleFilterSubmit: Provides filter submission logic integrated into document fetching.
Visual Diagram
flowchart TD
A[useUploadNextDocument] -->|Uploads files| KBService[KnowledgeBaseService]
B[useFetchDocumentList] -->|Fetches documents| KBService
B --> |Uses| useDebounce
B --> |Uses| useHandleSearchChange
B --> |Uses| useGetPaginationWithRouter
C[useGetDocumentFilter] -->|Fetches filters| KBService
D[useSetDocumentStatus] -->|Updates status| KBService
E[useRunDocument] -->|Runs documents| KBService
F[useRemoveDocument] -->|Removes documents| KBService
G[useSaveDocumentName] -->|Renames document| KBService
H[useSetDocumentParser] -->|Sets parser config| KBService
I[useSetDocumentMeta] -->|Updates metadata| KBService
J[useCreateDocument] -->|Creates document| KBService
KBService -->|API Calls| Backend[Backend API]
style KBService fill:#f9f,stroke:#333,stroke-width:2px
style Backend fill:#bbf,stroke:#333,stroke-width:2px
Summary
use-document-request.ts is a critical utility file in the knowledge base application that abstracts API interactions into React Query-powered hooks. These hooks enable UI components to manage documents efficiently with features like debounced search, pagination, filtering, real-time updates, and rich user feedback, all while maintaining synchronization with the backend service and application routing.