Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor routes and fix cluster passing in header #428

Merged
merged 2 commits into from
Jul 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 36 additions & 15 deletions dashboard/src/API/apiService.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,64 @@
import { Chart, ChartVersion, Release, ReleaseHealthStatus, Repository } from "../data/types";
import { QueryFunctionContext } from "@tanstack/react-query";

interface ClustersResponse {
AuthInfo: string
Cluster: string
IsCurrent: boolean
Name: string
Namespace: string
}
class ApiService {
constructor(protected readonly isMockMode: boolean = false) {}

currentCluster: string = "";

Check failure on line 11 in dashboard/src/API/apiService.ts

View workflow job for this annotation

GitHub Actions / static_and_lint

Type string trivially inferred from a string literal, remove type annotation
constructor(protected readonly isMockMode: boolean = false) { }

setCluster = (cluster: string) => {
this.currentCluster = cluster;
}

public fetchWithDefaults = async (url: string, options?: RequestInit) => {
if (this.currentCluster) {
const headers = new Headers(options?.headers);
if (!headers.has("X-Kubecontext")) {
headers.set("X-Kubecontext", this.currentCluster);
}
return fetch(url, { ...options, headers });
}
return fetch(url, options);
}
getToolVersion = async () => {
const response = await fetch(`/status`);
const data = await response.json();
return data;
};

getRepositoryLatestVersion = async (repositoryName: string) => {
const response = await fetch(
const response = await this.fetchWithDefaults(
`/api/helm/repositories/latestver?name=${repositoryName}`
);
const data = await response.json();
return data;
};

getInstalledReleases = async () => {
const response = await fetch(`/api/helm/releases`);
const response = await this.fetchWithDefaults(`/api/helm/releases`);
const data = await response.json();
return data;
};

getClusters = async () => {
const response = await fetch(`/api/k8s/contexts`);
const data = await response.json();
const data = (await response.json()) as ClustersResponse[];
return data;
};

getNamespaces = async () => {
const response = await fetch(`/api/k8s/namespaces/list`);
const response = await this.fetchWithDefaults(`/api/k8s/namespaces/list`);
const data = await response.json();
return data;
};

getRepositories = async () => {
const response = await fetch(`/api/helm/repositories`);
const response = await this.fetchWithDefaults(`/api/helm/repositories`);
const data = await response.json();
return data;
};
Expand All @@ -45,8 +66,8 @@
getRepositoryCharts = async ({
queryKey,
}: QueryFunctionContext<Chart[], Repository>) => {
const [_, repository] = queryKey;

Check warning on line 69 in dashboard/src/API/apiService.ts

View workflow job for this annotation

GitHub Actions / static_and_lint

'_' is assigned a value but never used
const response = await fetch(`/api/helm/repositories/${repository}`);
const response = await this.fetchWithDefaults(`/api/helm/repositories/${repository}`);
const data = await response.json();
return data;
};
Expand All @@ -54,9 +75,9 @@
getChartVersions = async ({
queryKey,
}: QueryFunctionContext<ChartVersion[], Chart>) => {
const [_, chart] = queryKey;

Check warning on line 78 in dashboard/src/API/apiService.ts

View workflow job for this annotation

GitHub Actions / static_and_lint

'_' is assigned a value but never used

const response = await fetch(
const response = await this.fetchWithDefaults(
`/api/helm/repositories/versions?name=${chart.name}`
);
const data = await response.json();
Expand All @@ -65,24 +86,24 @@

getResourceStatus = async ({
release,
}: { release: Release}) : Promise<ReleaseHealthStatus[] | null> => {
}: { release: Release }): Promise<ReleaseHealthStatus[] | null> => {
if (!release) return null;

const response = await fetch(
const response = await this.fetchWithDefaults(
`/api/helm/releases/${release.namespace}/${release.name}/resources?health=true`
);
const data = await response.json()
return data;
return data;
};

getReleasesHistory = async ({
queryKey,
}: QueryFunctionContext<Release[], Release>) => {
const [_, params] = queryKey;

Check warning on line 102 in dashboard/src/API/apiService.ts

View workflow job for this annotation

GitHub Actions / static_and_lint

'_' is assigned a value but never used

if (!params.namespace || !params.chart) return null;

const response = await fetch(
const response = await this.fetchWithDefaults(
`/api/helm/releases/${params.namespace}/${params.chart}/history`
);
const data = await response.json();
Expand All @@ -90,15 +111,15 @@
return data;
};

getValues = async ({ queryKey }: any) => {

Check warning on line 114 in dashboard/src/API/apiService.ts

View workflow job for this annotation

GitHub Actions / static_and_lint

Unexpected any. Specify a different type
const [_, params] = queryKey;

Check warning on line 115 in dashboard/src/API/apiService.ts

View workflow job for this annotation

GitHub Actions / static_and_lint

'_' is assigned a value but never used
const { namespace, chart, version } = params;

if (!namespace || !chart || !chart.name || version === undefined)
return Promise.reject(new Error("missing parameters"));

const url = `/api/helm/repositories/values?chart=${namespace}/${chart.name}&version=${version}`;
const response = await fetch(url);
const response = await this.fetchWithDefaults(url);
const data = await response.text();

return data;
Expand Down
5 changes: 3 additions & 2 deletions dashboard/src/API/releases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
} from "@tanstack/react-query";
import { ChartVersion, Release } from "../data/types";
import { LatestChartVersion } from "./interfaces";

import ApiService from "./apiService";
import apiService from "./apiService";
export const HD_RESOURCE_CONDITION_TYPE = "hdHealth"; // it's our custom condition type, only one exists

export function useGetInstalledReleases(
Expand Down Expand Up @@ -350,7 +351,7 @@ export async function callApi<T>(
url: string,
options?: RequestInit
): Promise<T> {
const response = await fetch(url, options);
const response = await apiService.fetchWithDefaults(url, options);

if (!response.ok) {
const error = await response.text();
Expand Down
102 changes: 55 additions & 47 deletions dashboard/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import Header from "./layout/Header";
import { HashRouter, Route, Routes } from "react-router-dom";
import { HashRouter, Outlet, Route, Routes, useLocation, useMatch, useParams } from "react-router-dom";
import "./index.css";
import Installed from "./pages/Installed";
import RepositoryPage from "./pages/Repository";
import Revision from "./pages/Revision";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useState } from "react";
import { PropsWithChildren, useContext, useEffect, useState } from "react";
import { ErrorAlert, ErrorModalContext } from "./context/ErrorModalContext";
import GlobalErrorModal from "./components/modal/GlobalErrorModal";
import { AppContextProvider } from "./context/AppContext";
import { AppContextProvider, useAppContext } from "./context/AppContext";
import apiService from "./API/apiService";

const queryClient = new QueryClient({
defaultOptions: {
Expand All @@ -18,19 +19,28 @@ const queryClient = new QueryClient({
},
});

const PageLayout = ({ children }: { children: React.ReactNode }) => {
const PageLayout = () => {
return (
<>
<Header />
<div className="bg-body-background min-h-screen min-w-screen">
<div className="bg-no-repeat bg-[url('./assets/body-background.svg')] min-h-screen max-h-full">
{children}
<Outlet />
</div>
</div>
</>
);
};

const SyncContext: React.FC = () => {
const { context } = useParams();
if (context) {
apiService.setCluster(context);
}

return <Outlet />;
}

export default function App() {
const [shouldShowErrorModal, setShowErrorModal] = useState<
ErrorAlert | undefined
Expand All @@ -43,48 +53,46 @@ export default function App() {
<ErrorModalContext.Provider value={value}>
<QueryClientProvider client={queryClient}>
<HashRouter>
<Routes>
<Route
path="/installed/:context?"
element={
<PageLayout>
<Installed />
</PageLayout>
}
/>
<Route
path="/installed/revision/:context/:namespace/:chart/:revision"
element={
<PageLayout>
<Revision />
</PageLayout>
}
/>
<Route
path="/repository/:context"
element={
<PageLayout>
<RepositoryPage />
</PageLayout>
}
/>
<Route
path="/repository/:context/:selectedRepo?"
element={
<PageLayout>
<RepositoryPage />
</PageLayout>
}
/>
<Route
path="*"
element={
<PageLayout>
<Installed />
</PageLayout>
}
/>
</Routes>
<Routes>
<Route path="*" element={<PageLayout />} >
<Route path=":context/*" element={<SyncContext />} >
<Route
path="installed/?"
element={<Installed />}
/>
<Route
path=":namespace/:chart/installed/revision/:revision"
element={
<Revision />
}
/>
<Route
path="repository/"
element={
<RepositoryPage />
}
/>
<Route
path="repository/:selectedRepo?"
element={
<RepositoryPage />
}
/>
<Route
path="*"
element={
<Installed />
}
/>
</Route>
<Route
path="*"
element={
<Installed />
}
/>
</Route>
</Routes>
<GlobalErrorModal
isOpen={!!shouldShowErrorModal}
onClose={() => setShowErrorModal(undefined)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export default function InstalledPackageCard({
}: InstalledPackageCardProps) {
const navigate = useNavigateWithSearchParams();

const { context: selectedCluster } = useParams();
const [isMouseOver, setIsMouseOver] = useState(false);

const { data: clusters } = useQuery<Cluster[]>({
Expand Down Expand Up @@ -64,16 +65,9 @@ export default function InstalledPackageCard({

const handleOnClick = () => {
const { name, namespace } = release;
const selectedCluster = clusters?.find((cluster) => cluster.IsCurrent);

if (!selectedCluster) {
throw new Error(
"Couldn't find selected cluster! cannot navigate to revision page"
);
}

navigate(
`/installed/revision/${selectedCluster?.Name}/${namespace}/${name}/${release.revision}`,
`/${selectedCluster}/${namespace}/${name}/installed/revision/${release.revision}`,
{ state: release }
);
};
Expand All @@ -87,11 +81,9 @@ export default function InstalledPackageCard({

return (
<div
className={`${
borderLeftColor[release.status]
} text-xs grid grid-cols-12 items-center bg-white rounded-md p-2 py-6 my-4 drop-shadow border-l-4 border-l-[${statusColor}] cursor-pointer ${
isMouseOver && "drop-shadow-lg"
}`}
className={`${borderLeftColor[release.status]
} text-xs grid grid-cols-12 items-center bg-white rounded-md p-2 py-6 my-4 drop-shadow border-l-4 border-l-[${statusColor}] cursor-pointer ${isMouseOver && "drop-shadow-lg"
}`}
onMouseOver={handleMouseOver}
onMouseOut={handleMouseOut}
onClick={handleOnClick}
Expand Down
2 changes: 1 addition & 1 deletion dashboard/src/components/modal/AddRepositoryModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function AddRepositoryModal({ isOpen, onClose }: AddRepositoryModalProps) {

queryClient.invalidateQueries({ queryKey: ["helm", "repositories"] });
setSelectedRepo(formData.name || "");
navigate(`/repository/${context}/${formData.name}`, { replace: true });
navigate(`/${context}/repository/${formData.name}`, { replace: true });
})
.catch((error) => {
alertError.setShowErrorModal({
Expand Down
Loading
Loading