use-knowledge-request.ts
Overview
The use-knowledge-request.ts file provides a collection of React hooks designed to interact with a knowledge base backend service. These hooks encapsulate various CRUD (Create, Read, Update, Delete) operations and data retrieval patterns related to knowledge bases, including fetching knowledge lists, creating or deleting knowledge entries, updating configurations, running retrieval tests, and fetching metadata or knowledge graphs.
The file integrates with the backend through a kbService API layer, leverages the powerful react-query library for asynchronous data fetching and caching, and uses React state and effects to manage UI interactions such as pagination, filtering, and search debouncing.
This file serves as a core utility within the application for managing knowledge base data, enabling components to easily consume and mutate knowledge-related data with automatic UI updates and caching.
Exports and Their Descriptions
Enumerations
KnowledgeApiAction
export const enum KnowledgeApiAction {
TestRetrieval = 'testRetrieval',
FetchKnowledgeListByPage = 'fetchKnowledgeListByPage',
CreateKnowledge = 'createKnowledge',
DeleteKnowledge = 'deleteKnowledge',
SaveKnowledge = 'saveKnowledge',
FetchKnowledgeDetail = 'fetchKnowledgeDetail',
FetchKnowledgeGraph = 'fetchKnowledgeGraph',
FetchMetadata = 'fetchMetadata',
}
Purpose: Provides a set of string constants representing different API actions related to knowledge base management.
Usage: Used as keys for query or mutation identifiers in
react-queryfor caching and invalidation.
Hooks
useKnowledgeBaseId
export const useKnowledgeBaseId = (): string;
Purpose: Extracts the knowledge base ID from the current URL parameters using Umi's
useParamshook.Returns: The knowledge base ID as a string. Returns an empty string if no ID is found.
Usage Example:
const kbId = useKnowledgeBaseId();
useTestRetrieval
export const useTestRetrieval = () => {
// returns:
// - data: INextTestingResult
// - loading: boolean
// - setValues: React.Dispatch<ITestRetrievalRequestBody>
// - refetch: () => void
// - onPaginationChange: (page: number, pageSize: number) => void
// - page: number
// - pageSize: number
// - handleFilterSubmit: () => void
// - filterValue: any
}
Purpose: Runs a retrieval test on a knowledge base with pagination and filtering support.
Parameters: None.
Return values:
data: Results of the retrieval test, including chunks, document aggregations, total count, and a flag indicating if the test has run.loading: Indicates if the query is currently fetching.setValues: Setter to update the request body for the test retrieval.refetch: Function to manually refetch the test retrieval data.onPaginationChange: Callback to update page number and size.page,pageSize: Current pagination state.handleFilterSubmit,filterValue: Filter bar related handlers and state.
Implementation details:
Uses
useQuerywith theKnowledgeApiAction.TestRetrievalkey.Debounces pagination and filter changes before fetching.
Uses a
mountedRefto skip the initial effect on mount.
Usage Example:
const { data, loading, setValues, refetch, onPaginationChange, page, pageSize, handleFilterSubmit, filterValue, } = useTestRetrieval();Notes: Designed for use in components that need to test knowledge retrieval with flexible filtering and pagination.
useFetchNextKnowledgeListByPage
export const useFetchNextKnowledgeListByPage = () => {
// returns:
// - kbs: IKnowledge[]
// - total: number
// - searchString: string
// - handleInputChange: React.ChangeEventHandler<HTMLInputElement>
// - pagination: { current: number; pageSize: number; total: number }
// - setPagination: React.Dispatch<...>
// - loading: boolean
// - filterValue: any
// - handleFilterSubmit: () => void
}
Purpose: Fetches a paginated list of knowledge bases, supporting search input with debouncing and filtering by owner.
Parameters: None.
Return values:
kbs: Array of knowledge base objects.total: Total count of knowledge bases matching criteria.searchString: Current search input string.handleInputChange: Event handler to update the search string.pagination: Current pagination state including total.setPagination: Setter for pagination state.loading: Indicates if fetching is in progress.filterValue,handleFilterSubmit: Filter bar related handlers and state.
Implementation details:
Uses
useDebouncefromahooksto debounce search input by 500ms.Uses custom hooks
useHandleSearchChangeanduseGetPaginationWithRouterto synchronize search and pagination state with the router.Runs
listDatasetAPI call, passing search keywords, pagination, and owner filters.
Usage Example:
const { kbs, total, searchString, handleInputChange, pagination, setPagination, loading, filterValue, handleFilterSubmit, } = useFetchNextKnowledgeListByPage();Notes: Useful for list views or dashboards showing knowledge bases with search and pagination controls.
useCreateKnowledge
export const useCreateKnowledge = () => {
// returns:
// - data: any
// - loading: boolean
// - createKnowledge: (params: { id?: string; name: string }) => Promise<any>
}
Purpose: Provides a mutation hook to create or modify a knowledge base.
Parameters: None.
Return values:
data: Response data from the create/modify API call.loading: Indicates if the mutation is in progress.createKnowledge: Async function to trigger creation or modification.
Implementation details:
Uses
useMutationfromreact-query.On success, shows a message (created or modified) and invalidates the knowledge list query for UI refresh.
Usage Example:
const { createKnowledge, loading } = useCreateKnowledge(); createKnowledge({ name: 'New KB' }).then(() => { // handle post creation logic });Notes: Supports optional
idparam to modify existing knowledge base.
useDeleteKnowledge
export const useDeleteKnowledge = () => {
// returns:
// - data: any
// - loading: boolean
// - deleteKnowledge: (id: string) => Promise<any>
}
Purpose: Provides a mutation hook to delete a knowledge base by ID.
Parameters: None.
Return values:
data: Response data from the delete API call.loading: Indicates if deletion is in progress.deleteKnowledge: Async function to trigger deletion.
Implementation details:
Uses
useMutation.Shows success message on completion.
Invalidates knowledge list queries to refresh UI.
Usage Example:
const { deleteKnowledge, loading } = useDeleteKnowledge(); deleteKnowledge('kb-id-123');Notes: Handles necessary cache invalidations post-deletion.
useUpdateKnowledge
export const useUpdateKnowledge = (shouldFetchList = false) => {
// returns:
// - data: any
// - loading: boolean
// - saveKnowledgeConfiguration: (params: Record<string, any>) => Promise<any>
}
Purpose: Provides a mutation hook to update knowledge base configurations.
Parameters:
shouldFetchList(boolean, optional): Whether to refresh the full knowledge list on update. Defaults tofalse.
Return values:
data: Response data from the update API call.loading: Indicates if mutation is in progress.saveKnowledgeConfiguration: Async function to trigger update.
Implementation details:
Uses knowledge base ID from URL params if not provided explicitly.
On success, shows success message.
Conditionally invalidates either the knowledge list or detail queries based on
shouldFetchList.
Usage Example:
const { saveKnowledgeConfiguration } = useUpdateKnowledge(true); saveKnowledgeConfiguration({ kb_id: 'kb-id', name: 'Updated Name' });Notes: Useful for updating settings or metadata of a knowledge base.
useFetchKnowledgeBaseConfiguration
export const useFetchKnowledgeBaseConfiguration = (refreshCount?: number) => {
// returns:
// - data: IKnowledge
// - loading: boolean
}
Purpose: Fetches detailed configuration or metadata of a knowledge base.
Parameters:
refreshCount(optional number): Used to force refetch by changing the query key.
Return values:
data: Knowledge base detail object.loading: Indicates if fetching is in progress.
Implementation details:
Uses URL params and search params to determine knowledge base ID.
Uses
useQuerywithKnowledgeApiAction.FetchKnowledgeDetailkey.
Usage Example:
const { data, loading } = useFetchKnowledgeBaseConfiguration();Notes: Reactively refetches when
refreshCountchanges, useful for manual refresh triggers.
useFetchKnowledgeGraph
export function useFetchKnowledgeGraph() {
// returns:
// - data: IKnowledgeGraph
// - loading: boolean
}
Purpose: Fetches the knowledge graph and mind map data associated with a knowledge base.
Parameters: None.
Return values:
data: The knowledge graph data.loading: Indicates if fetching is in progress.
Implementation details:
Uses
useKnowledgeBaseIdto get the current knowledge base ID.Calls
getKnowledgeGraphservice method.
Usage Example:
const { data, loading } = useFetchKnowledgeGraph();Notes: Disabled if no knowledge base ID is present.
useFetchKnowledgeMetadata
export function useFetchKnowledgeMetadata(kbIds: string[] = []) {
// returns:
// - data: Record<string, Record<string, string[]>>
// - loading: boolean
}
Purpose: Fetches metadata for one or more knowledge bases.
Parameters:
kbIds: Array of knowledge base IDs to fetch metadata for.
Return values:
data: A nested record mapping knowledge base IDs to their metadata fields.loading: Indicates if fetching is in progress.
Implementation details:
Disabled if
kbIdsarray is empty.Joins
kbIdsinto a comma-separated string for API request.
Usage Example:
const { data, loading } = useFetchKnowledgeMetadata(['kb1', 'kb2']);Notes: Useful for batch metadata retrieval.
Important Implementation Details and Algorithms
React Query Integration: The file extensively uses
react-queryhooks (useQuery,useMutation) to handle asynchronous data fetching, mutation, caching, and invalidation. This ensures UI components are updated reactively and efficiently.Debouncing: The search input in
useFetchNextKnowledgeListByPageis debounced usinguseDebouncefromahooksto minimize unnecessary API calls during user typing.URL Param Synchronization: The hooks use Umi's
useParamsanduseSearchParamsto synchronize knowledge base IDs and pagination states with the URL, allowing deep linking and browser navigation support.Filter Handling: Filtering is integrated via a custom
useHandleFilterSubmithook (imported from another module), enabling consistent filter state management.Cache Invalidation: After mutations (create, update, delete), relevant queries are invalidated via React Query's
queryClient.invalidateQueriesto refresh the UI data.Conditional Fetching: Some queries are disabled (
enabled: falseor conditional) until certain conditions are met, such as the presence of a knowledge base ID or a non-empty array of IDs.
Interaction with Other Parts of the System
API Service Layer (
kbService): All backend interactions go through this service, which encapsulates HTTP requests to the knowledge base server endpoints.UI Components: The hooks provide data and mutation functions to React components (e.g., knowledge base list views, detail pages, retrieval test components).
Localization (
i18n): Success messages for mutations are localized using the importedi18nconfiguration.Filtering Component (
useHandleFilterSubmit): The file depends on a filter bar hook to manage filter states applied to list retrieval.Routing and Pagination Hooks (
useGetPaginationWithRouter,useHandleSearchChange): These hooks synchronize pagination and search input with URL parameters, enabling better user experience and navigation.
Visual Diagram
classDiagram
class useKnowledgeBaseId {
+() : string
}
class useTestRetrieval {
- knowledgeBaseId: string
- values: ITestRetrievalRequestBody | undefined
- page: number
- pageSize: number
+() : {
data: INextTestingResult,
loading: boolean,
setValues: React.Dispatch,
refetch: () => void,
onPaginationChange: (number, number) => void,
page: number,
pageSize: number,
handleFilterSubmit: () => void,
filterValue: any
}
}
class useFetchNextKnowledgeListByPage {
- searchString: string
- pagination: { current: number; pageSize: number }
+() : {
kbs: IKnowledge[],
total: number,
searchString: string,
handleInputChange: React.ChangeEventHandler,
pagination: object,
setPagination: React.Dispatch,
loading: boolean,
filterValue: any,
handleFilterSubmit: () => void
}
}
class useCreateKnowledge {
+() : {
data: any,
loading: boolean,
createKnowledge: (params) => Promise<any>
}
}
class useDeleteKnowledge {
+() : {
data: any,
loading: boolean,
deleteKnowledge: (id: string) => Promise<any>
}
}
class useUpdateKnowledge {
+ (shouldFetchList?: boolean) : {
data: any,
loading: boolean,
saveKnowledgeConfiguration: (params) => Promise<any>
}
}
class useFetchKnowledgeBaseConfiguration {
+ (refreshCount?: number) : {
data: IKnowledge,
loading: boolean
}
}
class useFetchKnowledgeGraph {
+() : {
data: IKnowledgeGraph,
loading: boolean
}
}
class useFetchKnowledgeMetadata {
+ (kbIds: string[]) : {
data: Record<string, Record<string, string[]>>,
loading: boolean
}
}
useTestRetrieval ..> useKnowledgeBaseId : uses
useFetchKnowledgeGraph ..> useKnowledgeBaseId : uses
Summary
The use-knowledge-request.ts file is a centralized module of React hooks that abstract and standardize interactions with knowledge base APIs. It promotes consistent data handling, caching, and UI synchronization while providing convenient interfaces for components to perform knowledge base operations such as listing, creating, updating, deleting, and testing retrieval functionalities.
This modular approach improves maintainability, testability, and scalability of the knowledge base features in the application.