File size: 4,255 Bytes
5da4770
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
'use client';

import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
import { createQueryHook } from '@/hooks/use-query';
import { backendApi } from '@/lib/api-client';
import { 
  pipedreamApi, 
  type CreateConnectionTokenRequest,
  type ConnectionTokenResponse,
  type ConnectionResponse,
  type PipedreamAppResponse,
  type PipedreamToolsResponse,
  type AppIconResponse,
} from './utils';
import { pipedreamKeys } from './keys';

export const useCreateConnectionToken = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (request: CreateConnectionTokenRequest): Promise<ConnectionTokenResponse> => {
      return await pipedreamApi.createConnectionToken(request);
    },
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: pipedreamKeys.connections() });
      queryClient.setQueryData(pipedreamKeys.connectionToken(variables.app), data);
    },
    onError: (error) => {
      console.error('Failed to create connection token:', error);
    },
  });
};

export const useRefreshConnections = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (): Promise<ConnectionResponse> => {
      return await pipedreamApi.getConnections();
    },
    onSuccess: (data) => {
      queryClient.setQueryData(pipedreamKeys.connections(), data);
    },
    onError: (error) => {
      console.error('Failed to refresh connections:', error);
    },
  });
};

export const useInvalidatePipedreamQueries = () => {
  const queryClient = useQueryClient();
  return () => {
    queryClient.invalidateQueries({ queryKey: pipedreamKeys.all });
  };
}; 

export const usePipedreamApps = (after?: string, search?: string) => {
  return useQuery({
    queryKey: ['pipedream', 'apps', after, search],
    queryFn: async (): Promise<PipedreamAppResponse> => {
      const result = await pipedreamApi.getApps(after, search);
      console.log('🔍 Apps:', result);
      return result;
    },
    staleTime: 5 * 60 * 1000, 
    retry: 2,
  });
};

export const usePipedreamPopularApps = () => {
  return useQuery({
    queryKey: pipedreamKeys.popularApps(),
    queryFn: async (): Promise<PipedreamAppResponse> => {
      const result = await pipedreamApi.getPopularApps();
      console.log('🔍 Popular apps:', result);
      return result;
    },
    staleTime: 30 * 60 * 1000,
    retry: 2,
  });
};

export const usePipedreamAppIcon = (appSlug: string, options?: { enabled?: boolean }) => {
  return useQuery({
    queryKey: ['pipedream', 'app-icon', appSlug],
    queryFn: async (): Promise<AppIconResponse> => {
      const result = await pipedreamApi.getAppIcon(appSlug);
      console.log(`🎨 Icon for ${appSlug}:`, result);
      return result;
    },
    enabled: options?.enabled !== undefined ? options.enabled : !!appSlug,
    staleTime: 60 * 60 * 1000,
    retry: 2,
  });
};

export const usePipedreamAvailableTools = createQueryHook(
  pipedreamKeys.availableTools(),
  async (forceRefresh: boolean = false): Promise<PipedreamToolsResponse> => {
    const params = new URLSearchParams();
    if (forceRefresh) {
      params.append('force_refresh', 'true');
    }
    
    const url = `/pipedream/mcp/available-tools${params.toString() ? `?${params.toString()}` : ''}`;
    const result = await backendApi.get<PipedreamToolsResponse>(url, {
      errorContext: { operation: 'load available tools', resource: 'Pipedream tools' },
    });
    if (result.success && result.data) {
      if (result.data.success) {
        return result.data;
      } else {
        throw new Error(result.data.error || 'Failed to get available tools');
      }
    } else {
      throw new Error(result.error?.message || 'Failed to get available tools');
    }
  },
  {
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
    refetchOnWindowFocus: false,
    refetchOnMount: true,
    retry: (failureCount, error) => {
      if (failureCount < 2) {
        const errorMessage = error?.message?.toLowerCase() || '';
        return !errorMessage.includes('unauthorized') && !errorMessage.includes('forbidden');
      }
      return false;
    },
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
  }
);