/ src / api / discussion-messages.ts
discussion-messages.ts
 1  import { RequestFN } from "~/core/request-function";
 2  import { decodeDiscussionMessages } from "~/decoders/discussion-messages";
 3  import { type Discussion, DiscussionMessages, type SessionHandle, TabLocation } from "~/models";
 4  import { apiProperties } from "./private/api-properties";
 5  
 6  /**
 7   * Fetches the messages and writes them in the discussion.
 8   * By default it won't mark the messages as read even after fetching them.
 9   *
10   * You can change this behavior by setting `markAsRead` to `true`.
11   * There's no other way to mark the messages as read.
12   *
13   * @param session - The current session handle.
14   * @param discussion - The discussion object to fetch messages for.
15   * @param [markAsRead=false] Whether to mark the messages as read after fetching them.
16   */
17  export const discussionMessages = async (session: SessionHandle, discussion: Discussion, markAsRead: boolean = false): Promise<DiscussionMessages> => {
18    const properties = apiProperties(session);
19  
20    const request = new RequestFN(session, "ListeMessages", {
21      [properties.signature]: { onglet: TabLocation.Discussions },
22  
23      [properties.data]: {
24        listePossessionsMessages: discussion.possessions,
25        marquerCommeLu: markAsRead,
26        nbMessagesVus: 0 // fetch all messages
27      }
28    });
29  
30    const response = await request.send();
31    const messages = decodeDiscussionMessages(response.data[properties.data], session);
32  
33    if (!discussion.messages) // setup the reference
34      discussion.messages = messages;
35    else // mutate the reference
36      Object.assign(discussion.messages, messages);
37  
38    return messages;
39  };