hooks.ts
Overview
The hooks.ts file located in src/pages/next-searches provides a set of custom React hooks primarily focused on managing "search" entities within the application. These hooks facilitate CRUD (Create, Read, Update, Delete) operations and state management related to search configurations, leveraging React Query for asynchronous server state management and Umi.js for routing and parameter handling.
Key functionalities include:
Creating new search configurations.
Fetching lists of existing searches with filtering and pagination.
Fetching detailed information for a specific search.
Updating and deleting existing searches.
Handling UI modal state for renaming or creating searches.
Integration with translation and notification systems for UI feedback.
These hooks abstract away interaction with the underlying searchService API and encapsulate business logic and UI state management to be reused within React components.
Detailed Explanations
Interfaces and Types
CreateSearchProps
Parameters for creating a search.
Properties:
name: string— Name of the search.description?: string — Optional description.
CreateSearchResponse
Response shape when a search is created.
Properties:
id: stringname: stringdescription: string
SearchListParams
Parameters for fetching search lists.
Properties include optional filters and pagination:
keywords?: stringparser_id?: stringpage?: numberpage_size?: numberorderby?: stringdesc?: booleanowner_ids?: string
ISearchAppProps
Represents a search app summary item.
Properties like
id,name,description,status, timestamps, and tenant info.
SearchListResponse
API response for listing searches.
Contains an array of search_apps and
totalcount.
DeleteSearchProps
Parameters to delete a search.
search_id: string
DeleteSearchResponse
Response from deleting a search.
Includes
code,data(boolean), andmessage.
IllmSettingProps and IllmSettingEnableProps
Configuration for LLM (Large Language Model) parameters.
ISearchAppDetailProps
Detailed search app configuration including settings for language, documents, chat, highlighting, reranking, thresholds, and LLM settings.
SearchDetailResponse
Response object wrapping detailed search data.
IUpdateSearchProps
Used to update search details, includes all detailed search properties except
id, plussearch_id.
Hooks
useCreateSearch
Creates a new search entity.
Return Value:
data: The created search data (CreateSearchResponse | undefined).isError: Boolean indicating if an error occurred.createSearch(props: CreateSearchProps): Promise<CreateSearchResponse>: Function to trigger creation.
Usage Example:
const { createSearch, isError, data } = useCreateSearch();
await createSearch({ name: 'My Search', description: 'Test search' });
Details:
Uses
useMutationfrom React Query.Calls
searchService.createSearch.Shows success or error messages via UI message component.
Localized with
react-i18next.
useFetchSearchList(params?: SearchListParams)
Fetches a paginated list of searches based on filter parameters.
Parameters:
params(optional): Initial search parameters.
Return Value:
data: The search list response.isLoading: Loading state boolean.isError: Error state boolean.searchParams: Current search parameters state.setSearchListParams(newParams: SearchListParams): Function to update search params and trigger refetch.refetch(): Manually refetch the list.
Usage Example:
const {
data,
isLoading,
searchParams,
setSearchListParams,
} = useFetchSearchList({ keywords: 'example' });
setSearchListParams({ page: 2 });
Details:
Uses
useQuerywith the key['searchList', searchParams].Updates internal state for pagination and filters.
Calls
searchService.getSearchList.
useFetchSearchDetail(tenantId?: string)
Fetches detailed information for a specific search.
Parameters:
tenantId(optional): Tenant ID used when accessing shared search details.
Return Value:
data: Detailed search data (ISearchAppDetailProps | undefined).isLoading: Loading state.isError: Error state.
Details:
Reads
search_idfrom route params or shared query params.Chooses between two API endpoints:
getSearchDetailfor normal access.getSearchDetailSharefor shared searches.
Uses
useQuerywith the key['searchDetail', searchId].Disabled until tenantId is available when using shared search.
useDeleteSearch
Deletes a search entity.
Return Value:
data: Delete response data.isError: Error state.deleteSearch(props: DeleteSearchProps): Promise<DeleteSearchResponse>: Function to trigger delete.
Usage Example:
const { deleteSearch } = useDeleteSearch();
await deleteSearch({ search_id: '1234' });
Details:
Uses
useMutation.Calls
searchService.deleteSearch.On success, invalidates
searchListqueries to refresh data.Shows localized success or error UI messages.
useUpdateSearch
Updates search details.
Return Value:
data: Updated search data.isError: Error state.updateSearch(formData: IUpdateSearchProps): Promise<any>: Function to trigger update.
Usage Example:
const { updateSearch } = useUpdateSearch();
await updateSearch({ search_id: '1234', name: 'Updated Name', ...otherDetails });
Details:
Uses
useMutation.Calls
searchService.updateSearchSetting.On success, invalidates
searchDetailquery for the updated search.Shows success/error messages.
useRenameSearch
Manages UI state and logic to rename or create a search via modal dialogs.
Return Value:
searchRenameLoading: Boolean loading state for rename/create operation.initialSearchName: Initial name shown in the modal input.onSearchRenameOk(name: string, callBack?: () => void): Function called on modal confirmation to create or update a search.openCreateModal: Boolean indicating if the modal is open.hideSearchRenameModal(): Hide the rename modal.showSearchRenameModal(record?: ISearchAppProps): Show the rename modal optionally with existing search data.
Usage Example:
const {
showSearchRenameModal,
hideSearchRenameModal,
onSearchRenameOk,
searchRenameLoading,
} = useRenameSearch();
// To open modal for existing search:
showSearchRenameModal(searchRecord);
// To confirm rename:
await onSearchRenameOk('New Search Name');
Details:
Uses internal state to track which search is being renamed.
Uses
useUpdateSearchanduseCreateSearchto perform operations.Navigates to new search page if a new search is created.
Interfaces with modal visibility via
useSetModalState.Uses
searchService.getSearchDetailto fetch current details before update.Handles loading state and modal visibility.
Important Implementation Details
React Query Integration:
All data fetching and mutations are handled using React Query's
useQueryanduseMutationhooks.This enables caching, automatic refetching, and optimistic updates.
Queries are keyed appropriately to allow fine-grained cache invalidation.
Error Handling & Notifications:
On mutation success or failure, user feedback is provided via the
messageUI component.Errors throw exceptions if API response codes are non-zero.
Localization:
The translation hook
useTranslationfromreact-i18nextis used for all UI messages, facilitating internationalization.
Routing and Params:
Uses
useParamsanduseSearchParamsfrom Umi.js to extract route and query parameters.Supports shared search access with tenant ID.
Modal State Management:
The
useRenameSearchhook uses a custom hookuseSetModalStateto control modal visibility, enhancing UI state separation.
API Service Abstraction:
All server interactions delegate to
searchService, centralizing API calls and response handling.
Interaction with Other System Parts
API Layer:
Relies on
searchServicefor backend communication.Expected to align with backend API specifications for search management.
UI Components:
Uses UI components for notification (
message).Modal display is controlled with
useSetModalStatehook, presumably shared across the UI layer.
Routing:
Integrates with Umi.js routing for navigation and parameter extraction.
useNavigatePagehook is used to navigate programmatically after search creation.
State Management:
React Query manages asynchronous server state.
React's
useStatemanages local UI state in some hooks.
Mermaid Diagram: Flowchart of Main Hook Functions and Their Relationships
flowchart TD
A[useCreateSearch] -->|Calls| SVC_Create[searchService.createSearch]
B[useFetchSearchList] -->|Calls| SVC_List[searchService.getSearchList]
C[useFetchSearchDetail] -->|Calls| SVC_Detail[searchService.getSearchDetail / getSearchDetailShare]
D[useDeleteSearch] -->|Calls| SVC_Delete[searchService.deleteSearch]
E[useUpdateSearch] -->|Calls| SVC_Update[searchService.updateSearchSetting]
F[useRenameSearch] -->|Uses| A
F -->|Uses| E
F -->|Uses Modal Controls| Modal[useSetModalState]
F -->|Uses Navigation| Nav[useNavigatePage]
F -->|Reads Search Detail| SVC_Detail
style A fill:#f9f,stroke:#333,stroke-width:1px
style B fill:#ccf,stroke:#333,stroke-width:1px
style C fill:#ccf,stroke:#333,stroke-width:1px
style D fill:#f99,stroke:#333,stroke-width:1px
style E fill:#9f9,stroke:#333,stroke-width:1px
style F fill:#fc9,stroke:#333,stroke-width:1px
Summary
The hooks.ts file is a crucial abstraction layer managing asynchronous operations and UI state related to search management in the application. It cleanly encapsulates API interactions, UI feedback, localization, and modal state, exposing simple hook interfaces to React components. By leveraging React Query and custom hooks, it promotes maintainability, consistency, and reusability across the search-related features of the system.