Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

2.2 KB
Raw Blame
import { isNil } from '@activepieces/core-utils';
import { UserWithMetaInformation } from '@activepieces/shared';
import {
  QueryClient,
  useMutation,
  useQuery,
  useSuspenseQuery,
} from '@tanstack/react-query';

import { userApi } from '@/api/user-api';
import { authenticationSession } from '@/lib/authentication-session';

export const userHooks = {
  useCurrentUser: () => {
    const userId = authenticationSession.getCurrentUserId();
    const token = authenticationSession.getToken();
    const expired = authenticationSession.isJwtExpired(token!);
    return useSuspenseQuery<UserWithMetaInformation | null, Error>({
      queryKey: ['currentUser', userId],
      queryFn: async () => {
        // Skip user data fetch if JWT is expired to prevent redirect to sign-in page
        // This is especially important for embedding scenarios where we need to accept
        // a new JWT token rather than triggering the global error handler

        if (!userId || expired) {
          return null;
        }
        try {
          const result = await userApi.getUserById(userId);
          return result;
        } catch (error) {
          console.error(error);
          return null;
        }
      },
      staleTime: Infinity,
    });
  },
  useUserById: (id: string | null) => {
    return useQuery({
      queryKey: ['user', id],
      queryFn: async () => {
        try {
          return await userApi.getUserById(id!);
        } catch (error) {
          console.error(error);
          return null;
        }
      },
      enabled: !isNil(id),
      staleTime: Infinity,
    });
  },
  invalidateCurrentUser: (queryClient: QueryClient) => {
    const userId = authenticationSession.getCurrentUserId();
    queryClient.invalidateQueries({ queryKey: ['currentUser', userId] });
  },
  getCurrentUserPlatformRole: () => {
    const { data: user } = userHooks.useCurrentUser();
    return user?.platformRole;
  },
};

export const userMutations = {
  useUploadProfilePicture: ({
    onSuccess,
    onError,
  }: {
    onSuccess: () => void;
    onError: (error: Error) => void;
  }) => {
    return useMutation({
      mutationFn: (file: File) => userApi.updateMe(file),
      onSuccess,
      onError,
    });
  },
};