function useImportGraphMutation()

in packages/graph-explorer/src/modules/GraphViewer/ImportGraphButton.tsx [43:125]


function useImportGraphMutation() {
  const queryClient = useQueryClient();
  const explorer = useExplorer();
  const addToGraph = useAddToGraph();
  const allConfigs = useAtomValue(configurationAtom);
  const allConnections = allConfigs
    .values()
    .map(config =>
      config.connection
        ? {
            ...config.connection,
            id: config.id,
            displayLabel: config.displayLabel,
          }
        : null
    )
    .filter(c => c != null)
    .toArray();

  const { enqueueNotification, clearNotification } = useNotification();

  const notificationTitle = "Loading Graph";

  const mutation = useMutation({
    mutationFn: async (file: File) => {
      // 1. Parse the file
      const data = await fromFileToJson(file);
      const graph = await parseExportedGraph(data);

      // 2. Check connection
      if (!isMatchingConnection(explorer.connection, graph.connection)) {
        throw new InvalidConnectionError(
          "Connection must match active connection",
          graph.connection
        );
      }

      // 3. Get the vertex and edge details from the database
      const entityCountMessage = formatEntityCounts(
        graph.vertices.size,
        graph.edges.size
      );

      const progressNotificationId = enqueueNotification({
        title: notificationTitle,
        message: `Loading the graph with ${entityCountMessage} from the file "${file.name}"`,
        type: "loading",
        autoHideDuration: null,
      });

      const result = await fetchEntityDetails(
        graph.vertices,
        graph.edges,
        queryClient,
        explorer
      );

      clearNotification(progressNotificationId);

      return result;
    },
    onSuccess: async result => {
      // 4. Update Graph Explorer state
      await addToGraph(result.entities);

      // 5. Notify user of completion
      const finalNotification =
        createFetchEntityDetailsCompletionNotification(result);
      enqueueNotification({
        ...finalNotification,
        title: notificationTitle,
      });
    },
    onError: (error, file) => {
      const notification = createErrorNotification(error, file, allConnections);
      enqueueNotification({
        ...notification,
        title: notificationTitle,
      });
    },
  });
  return mutation;
}