useClusterList.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { useContext } from "react";
  2. import { useQuery } from "@tanstack/react-query";
  3. import { z } from "zod";
  4. import api from "shared/api";
  5. import { Context } from "shared/Context";
  6. export const clusterValidator = z.object({
  7. id: z.number(),
  8. name: z.string(),
  9. vanity_name: z.string(),
  10. cloud_provider: z.enum(["AWS", "GCP", "AZURE"]),
  11. });
  12. export type Cluster = z.infer<typeof clusterValidator>;
  13. export const isAWSCluster = (
  14. cluster: Cluster
  15. ): cluster is Cluster & { cloud_provider: "AWS" } => {
  16. return cluster.cloud_provider === "AWS";
  17. };
  18. type TUseClusterList = {
  19. clusters: Array<z.infer<typeof clusterValidator>>;
  20. isLoading: boolean;
  21. };
  22. export const useClusterList = (): TUseClusterList => {
  23. const { currentProject } = useContext(Context);
  24. const clusterReq = useQuery(
  25. ["getClusters", currentProject?.id],
  26. async () => {
  27. if (!currentProject?.id || currentProject.id === -1) {
  28. return;
  29. }
  30. const res = await api.getClusters(
  31. "<token>",
  32. {},
  33. { id: currentProject.id }
  34. );
  35. const parsed = await z.array(clusterValidator).parseAsync(res.data);
  36. return parsed;
  37. },
  38. {
  39. enabled: !!currentProject && currentProject.id !== -1,
  40. }
  41. );
  42. return {
  43. clusters: clusterReq.data ?? [],
  44. isLoading: clusterReq.isLoading,
  45. };
  46. };