use-chat-request.ts


Overview

The use-chat-request.ts file is a TypeScript module designed for managing chat-related data fetching, state mutation, and user interactions in a React-based frontend application. It provides a collection of React hooks that encapsulate asynchronous API calls and client-side state updates for dialogs and conversations within a chat system. These hooks utilize the React Query library for data fetching and cache management, along with utilities like lodash, ahooks, and umi for enhanced React state and URL parameter management.

The module covers a broad range of functionalities such as:

This file acts as a bridge between the frontend components and the backend chat services (chatService), abstracting away the details of API communication and providing a clean, reusable interface for chat data management.


Detailed Explanations

Enumerations

ChatApiAction

An enumeration listing string constants representing various API actions related to chat operations. These constants are used as query or mutation keys in React Query for cache and state management.

Enum Key

Description

FetchDialogList

Fetch list of dialogs

RemoveDialog

Remove dialogs

SetDialog

Create or update a dialog

FetchDialog

Fetch a single dialog

FetchConversationList

Fetch list of conversations

FetchConversation

Fetch a single conversation

UpdateConversation

Update a conversation

RemoveConversation

Remove conversations

DeleteMessage

Delete a message

FetchMindMap

Fetch mind map data

FetchRelatedQuestions

Fetch related questions

UploadAndParse

Upload and parse a file

FetchExternalChatInfo

Fetch external chat information


Hooks

useGetChatSearchParams()

Extracts chat-related parameters from the current URL search params.

{
  dialogId: string;         // ID of the dialog from URL or empty string
  conversationId: string;   // ID of the conversation from URL or empty string
  isNew: string;            // Flag indicating if it is a new conversation
}
const { dialogId, conversationId, isNew } = useGetChatSearchParams();

useClickDialogCard()

Provides a handler to update URL search params when a dialog card is clicked.

{
  handleClickDialog: (dialogId: string) => void;  // Function to update URL query with dialogId
}
const { handleClickDialog } = useClickDialogCard();
<button onClick={() => handleClickDialog('dialog123')}>Open Dialog</button>;

useFetchDialogList()

Manages fetching a paginated, searchable list of dialogs.

Property

Description

data

Object containing dialogs array and total count

loading

Boolean indicating if fetch is in progress

refetch

Function to manually refetch dialogs

searchString

Current search input string

handleInputChange

Input change handler to update search string

pagination

Pagination object with current page, size, total

setPagination

Function to update pagination

Uses a debounced search string (500ms delay) to avoid excessive API calls. Fetches data with chatService.listDialog.

const {
  data,
  loading,
  searchString,
  handleInputChange,
  pagination,
  setPagination,
} = useFetchDialogList();

useRemoveDialog()

Provides mutation to remove dialogs by their IDs.

{
  data: any;                    // Response data from API
  loading: boolean;             // Loading state of the mutation
  removeDialog: (dialogIds: string[]) => Promise<number>;  // Function to invoke deletion
}

useSetDialog()

Handles creation or modification of dialogs.

{
  data: any;                    // API response data
  loading: boolean;             // Loading state
  setDialog: (params: Partial<IDialog>) => Promise<number>;  // Function to set dialog data
}

useFetchDialog()

Fetches individual dialog details based on URL parameter id.

{
  data: IDialog;                // Dialog object
  loading: boolean;             // Loading state
  refetch: () => void;          // Function to refetch dialog data
}

Conversation Related Hooks

useClickConversationCard()

Updates URL search params with selected conversation ID and newness flag.

{
  handleClickConversation: (conversationId: string, isNew: string) => void;
}

useFetchConversationList()

Fetches a list of conversations for a given dialog ID from URL params.

{
  data: IConversation[];         // Array of conversations
  loading: boolean;              // Loading state
  refetch: () => void;           // Refetch function
  searchString: string;          // Search string for filtering conversations
  handleInputChange: React.ChangeEventHandler<HTMLInputElement>;
}

useFetchConversation()

Fetches detailed conversation data including messages, considering if conversation is new or shared.

{
  data: IClientConversation;    // Detailed conversation with messages containing UUIDs
  loading: boolean;             // Loading state
  refetch: () => void;          // Refetch function
}

useUpdateConversation()

Provides mutation to update conversation data.

{
  data: any;                    // API response data
  loading: boolean;             // Loading state
  updateConversation: (params: Record<string, any>) => Promise<any>;
}

useRemoveConversation()

Removes conversations by their IDs.

{
  data: any;                    // API response data
  loading: boolean;             // Loading state
  removeConversation: (conversationIds: string[]) => Promise<number>;
}

useDeleteMessage()

Deletes a single message within the current conversation.

{
  data: any;                    // API response data
  loading: boolean;             // Loading state
  deleteMessage: (messageId: string) => Promise<number>;
}

File Upload and Parsing Hook

useUploadAndParseFile()

Manages uploading a file related to a conversation, parsing it on the backend, and tracking upload progress.

{
  data: any;                    // API response data
  loading: boolean;             // Loading state
  uploadAndParseFile: (params: X) => Promise<any>;  // Upload function
  cancel: () => void;           // Cancels ongoing upload
}
type X = {
  file: File;                   // File object to upload
  options: {
    onProgress: (file: File, percent: number) => void;
    onSuccess: (file: File) => void;
    onError: (file: File, error: Error) => void;
  };
  conversationId?: string;      // Optional conversation ID override
};

External Chat Info Hook

useFetchExternalChatInfo()

Fetches external chat information based on a shared ID.

{
  data: IExternalChatInfo;      // External chat information object
  loading: boolean;             // Loading state
  refetch: () => void;          // Refetch function
}

Search Page Related Hooks

useFetchMindMap()

Fetches mind map data based on a request body.

{
  data: any;                    // Mind map data
  loading: boolean;             // Loading state
  fetchMindMap: (params: IAskRequestBody) => Promise<any>;
}

useFetchRelatedQuestions()

Fetches a list of related questions given a question string.

{
  data: string[];               // Array of related questions
  loading: boolean;             // Loading state
  fetchRelatedQuestions: (question: string) => Promise<string[]>;
}

Important Implementation Details


Interactions with Other Parts of the System


Visual Diagram

classDiagram
    class use-chat-request {
        <<hooks module>>
    }

    %% Hooks as methods
    use-chat-request : +useGetChatSearchParams()
    use-chat-request : +useClickDialogCard()
    use-chat-request : +useFetchDialogList()
    use-chat-request : +useRemoveDialog()
    use-chat-request : +useSetDialog()
    use-chat-request : +useFetchDialog()
    use-chat-request : +useClickConversationCard()
    use-chat-request : +useFetchConversationList()
    use-chat-request : +useFetchConversation()
    use-chat-request : +useUpdateConversation()
    use-chat-request : +useRemoveConversation()
    use-chat-request : +useDeleteMessage()
    use-chat-request : +useUploadAndParseFile()
    use-chat-request : +useFetchExternalChatInfo()
    use-chat-request : +useFetchMindMap()
    use-chat-request : +useFetchRelatedQuestions()

    %% External dependencies
    chatService <.. use-chat-request : uses
    message <.. use-chat-request : uses for notifications
    ReactQuery <.. use-chat-request : uses (useQuery, useMutation)
    umi <.. use-chat-request : uses (useSearchParams, useParams)

Summary

This file provides a comprehensive set of React hooks that serve as the data layer for chat interactions in the frontend. It abstracts API calls, state management, and user interactions related to dialogs, conversations, messages, and auxiliary data fetching. The design leverages modern React patterns and libraries to ensure a responsive, consistent, and maintainable chat experience.


End of Documentation for use-chat-request.ts