blob: f89d5e9a98318b1e23e46228e39f3b6f7dddd6ca [file] [log] [blame]
simon26e79f72022-10-05 22:16:08 -04001/*
2 * Copyright (C) 2022 Savoir-faire Linux Inc.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation; either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public
15 * License along with this program. If not, see
16 * <https://www.gnu.org/licenses/>.
17 */
simond47ef9e2022-09-28 22:24:28 -040018import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
19import axios from 'axios';
idillon08f77172022-09-13 19:14:17 -040020
simon35378692022-10-02 23:25:57 -040021export const useConversationQuery = (accountId: string, conversationId: string) => {
simond47ef9e2022-09-28 22:24:28 -040022 return useQuery(['conversation', accountId, conversationId], () => fetchConversation(accountId, conversationId), {
23 enabled: !!(accountId && conversationId),
24 });
25};
idillon08f77172022-09-13 19:14:17 -040026
simon35378692022-10-02 23:25:57 -040027export const useMessagesQuery = (accountId: string, conversationId: string) => {
simond47ef9e2022-09-28 22:24:28 -040028 return useQuery(['messages', accountId, conversationId], () => fetchMessages(accountId, conversationId), {
29 enabled: !!(accountId && conversationId),
30 });
31};
idillon08f77172022-09-13 19:14:17 -040032
simon35378692022-10-02 23:25:57 -040033export const useSendMessageMutation = (accountId: string, conversationId: string) => {
simond47ef9e2022-09-28 22:24:28 -040034 const queryClient = useQueryClient();
35 return useMutation(
simon35378692022-10-02 23:25:57 -040036 (message: string) => axios.post(`/api/accounts/${accountId}/conversations/${conversationId}`, { message }),
simond47ef9e2022-09-28 22:24:28 -040037 {
38 onSuccess: () => queryClient.invalidateQueries(['messages', accountId, conversationId]),
39 }
40 );
41};
idillonea465602022-09-13 19:58:51 -040042
simon35378692022-10-02 23:25:57 -040043const fetchConversation = (accountId: string, conversationId: string) =>
simond47ef9e2022-09-28 22:24:28 -040044 axios.get(`/api/accounts/${accountId}/conversations/${conversationId}`).then((result) => result.data);
idillon08f77172022-09-13 19:14:17 -040045
simon35378692022-10-02 23:25:57 -040046const fetchMessages = (accountId: string, conversationId: string) =>
simond47ef9e2022-09-28 22:24:28 -040047 axios.get(`/api/accounts/${accountId}/conversations/${conversationId}/messages`).then((result) => result.data);