File size: 1,655 Bytes
9b906ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React from "react";
import { QueryClientContext, useQuery } from "@tanstack/react-query";
import AutomationService from "#/api/automation-service/automation-service.api";
import { isNoBackend } from "#/api/backend-registry/active-store";
import { useActiveBackend } from "#/contexts/active-backend-context";
import { getQueryClient } from "#/query-client-config";

export const AUTOMATION_SDK_VERSION_CACHE_NAMESPACE = "automation-sdk-version";

const AUTOMATION_SDK_VERSION_CACHE_TIME_MS = 60 * 60 * 1000;
async function fetchAutomationSdkVersion(): Promise<string | null> {
  if (typeof AutomationService.getSdkVersion !== "function") {
    return null;
  }

  try {
    return await AutomationService.getSdkVersion();
  } catch {
    return null;
  }
}

export function useAutomationSdkVersion() {
  const active = useActiveBackend();
  const { backend } = active;
  const providerQueryClient = React.useContext(QueryClientContext);
  const canFetchSdkVersion =
    !isNoBackend(backend) &&
    typeof AutomationService.getSdkVersion === "function";
  const { data } = useQuery(
    {
      queryKey: [
        AUTOMATION_SDK_VERSION_CACHE_NAMESPACE,
        backend.id,
        backend.kind,
        backend.host,
        active.orgId ?? "",
      ],
      queryFn: fetchAutomationSdkVersion,
      enabled: canFetchSdkVersion,
      initialData: canFetchSdkVersion ? undefined : null,
      staleTime: AUTOMATION_SDK_VERSION_CACHE_TIME_MS,
      gcTime: AUTOMATION_SDK_VERSION_CACHE_TIME_MS,
      refetchOnWindowFocus: false,
      refetchOnReconnect: false,
    },
    providerQueryClient ?? getQueryClient(),
  );

  return data ?? null;
}