blob: 5440135178cb4fd76a5eae24d4b905ae2b18490f [file] [log] [blame]
idillon847b4642022-12-29 14:28:38 -05001/*
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 */
18import { useMutation, useQuery } from '@tanstack/react-query';
19import { ContactDetails, LookupResult } from 'jami-web-common';
20
21import { useAuthContext } from '../contexts/AuthProvider';
22import { Contact } from '../models/contact';
23import { useRefreshConversationsSummaries } from './conversationQueries';
24
25export const useContactsSearchQuery = (searchQuery: string) => {
26 const { axiosInstance } = useAuthContext();
27 return useQuery({
idillon2ef2be92022-12-30 10:59:06 -050028 queryKey: ['ns', 'username', searchQuery],
idillon847b4642022-12-29 14:28:38 -050029 queryFn: async () => {
30 const { data } = await axiosInstance.get<LookupResult>(`/ns/username/${searchQuery}`);
31 return data ? [new Contact(data.address, data.username)] : [];
32 },
33 enabled: !!searchQuery,
34 });
35};
36
idillon18283ac2023-01-07 12:06:42 -050037export const useContactQuery = (contactId?: string) => {
38 const { axiosInstance } = useAuthContext();
39
40 return useQuery({
41 queryKey: ['contacts', contactId],
42 queryFn: async () => {
43 const { data } = await axiosInstance.get<ContactDetails>(`/contacts/${contactId}`);
44 return data;
45 },
46 enabled: !!contactId,
47 });
48};
49
idillon847b4642022-12-29 14:28:38 -050050export const useAddContactMutation = () => {
51 const { axiosInstance } = useAuthContext();
52
53 const refreshConversationsSummaries = useRefreshConversationsSummaries();
54
55 return useMutation({
56 mutationFn: async (contactId: string) => {
57 const { data } = await axiosInstance.put<ContactDetails>(`/contacts/${contactId}`);
58 return data;
59 },
60 onSuccess: () => {
61 refreshConversationsSummaries();
62 },
63 });
64};