Skip to content
This repository has been archived by the owner on Jul 2, 2024. It is now read-only.

Commit

Permalink
Merge branch 'main' into DEVPROD-826
Browse files Browse the repository at this point in the history
  • Loading branch information
khelif96 committed Jan 25, 2024
2 parents aa7a343 + 23b1ce0 commit 5e16fbf
Show file tree
Hide file tree
Showing 10 changed files with 121 additions and 122 deletions.
8 changes: 4 additions & 4 deletions cypress/integration/host/host_events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { clickOnPageSizeBtnAndAssertURLandTableSize } from "../../utils";

describe("Host events", () => {
const pathWithEvents = "/host/i-0f81a2d39744003dd";
const dataCyTableRows = "[data-cy=host-events-table] .ant-table-row";
const dataCyTableRows = "[data-cy=host-events-table]";

beforeEach(() => {
cy.window().then((win) => {
Expand Down Expand Up @@ -217,9 +217,9 @@ describe("Host events", () => {
cy.contains("Hawaii").click();
cy.contains("button", "Save Changes").click();
cy.visit(pathWithEvents);
cy.dataCy("HOST_JASPER_RESTARTING-time").contains(
"Sep 30, 2017, 9:11:16 AM",
);
cy.dataCy("leafygreen-table-row")
.first()
.contains("Sep 30, 2017, 9:11:16 AM");
// Reset timezone so re-running this test works.
cy.visit("/preferences");
cy.contains("Hawaii").click();
Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "spruce",
"version": "3.0.194",
"version": "3.0.195",
"private": true,
"scripts": {
"bootstrap-logkeeper": "./scripts/bootstrap-logkeeper.sh",
Expand Down Expand Up @@ -103,7 +103,6 @@
"@sentry/types": "7.56.0",
"ansi_up": "6.0.2",
"antd": "4.20.0",
"axios": "1.6.1",
"date-fns": "2.28.0",
"date-fns-tz": "2.0.0",
"deep-object-diff": "1.1.9",
Expand Down
11 changes: 4 additions & 7 deletions src/gql/generated/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7112,13 +7112,10 @@ export type ProjectHealthViewQueryVariables = Exact<{

export type ProjectHealthViewQuery = {
__typename?: "Query";
projectSettings: {
__typename?: "ProjectSettings";
projectRef?: {
__typename?: "Project";
id: string;
projectHealthView: ProjectHealthView;
} | null;
project: {
__typename?: "Project";
id: string;
projectHealthView: ProjectHealthView;
};
};

Expand Down
8 changes: 3 additions & 5 deletions src/gql/queries/project-health-view.graphql
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
query ProjectHealthView($identifier: String!) {
projectSettings(identifier: $identifier) {
projectRef {
id
projectHealthView
}
project(projectIdentifier: $identifier) {
id
projectHealthView
}
}
2 changes: 1 addition & 1 deletion src/pages/commits/ViewToggle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export const ViewToggle: React.FC<Props> = ({ identifier }) => {

useEffect(() => {
if (!view) {
setView(data?.projectSettings?.projectRef?.projectHealthView);
setView(data?.project?.projectHealthView);
}
}, [data, setView, view]);

Expand Down
83 changes: 47 additions & 36 deletions src/pages/host/HostTable.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
import { useMemo } from "react";
import { useMemo, useRef } from "react";
import { ApolloError } from "@apollo/client";
import styled from "@emotion/styled";
import {
V10Table as Table,
V10TableHeader as TableHeader,
V10HeaderRow as HeaderRow,
V10Row as Row,
V10Cell as Cell,
V11Adapter,
} from "@leafygreen-ui/table";
import { useLeafyGreenTable, LGColumnDef } from "@leafygreen-ui/table";
import { Subtitle, SubtitleProps } from "@leafygreen-ui/typography";
import { useHostsTableAnalytics } from "analytics";
import PageSizeSelector, {
usePageSizeSelector,
} from "components/PageSizeSelector";
import Pagination from "components/Pagination";
import { BaseTable } from "components/Table/BaseTable";
import { size } from "constants/tokens";
import { HostEventsQuery } from "gql/generated/types";
import { useDateFormat } from "hooks";
import { HostCard } from "pages/host/HostCard";
import { HostEventString } from "pages/host/HostEventString";
import { Unpacked } from "types/utils";

type HostEvent = Unpacked<HostEventsQuery["hostEvents"]["eventLogEntries"]>;

export const HostTable: React.FC<{
loading: boolean;
Expand All @@ -43,10 +40,42 @@ export const HostTable: React.FC<{
hostsTableAnalytics.sendEvent({ name: "Change Page Size" });
};

const columns: LGColumnDef<HostEvent>[] = useMemo(
() => [
{
header: "Date",
accessorKey: "timestamp",
cell: ({ getValue }) => getDateCopy(getValue() as Date),
},
{
header: "Event",
accessorKey: "eventType",
cell: ({ getValue, row }) => (
<HostEventString
eventType={getValue() as string}
data={row.original.data}
/>
),
},
],
[getDateCopy],
);

const tableContainerRef = useRef<HTMLDivElement>(null);
const table = useLeafyGreenTable<HostEvent>({
columns,
containerRef: tableContainerRef,
data: logEntries ?? [],
defaultColumn: {
enableColumnFilter: false,
},
manualPagination: true,
});

return (
<HostCard error={error} loading={loading} metaData={false}>
<TableTitle>
<StyledSubtitle>Recent Events </StyledSubtitle>
<StyledSubtitle>Recent Events</StyledSubtitle>
<PaginationWrapper>
<Pagination
data-cy="host-event-table-pagination"
Expand All @@ -61,32 +90,14 @@ export const HostTable: React.FC<{
/>
</PaginationWrapper>
</TableTitle>
<V11Adapter shouldAlternateRowColor>
<Table
data-cy="host-events-table"
data={logEntries}
columns={
<HeaderRow>
<TableHeader key="date" dataType="date" label="Date" />
<TableHeader key="event" label="Event" />
</HeaderRow>
}
>
{({ datum }) => (
<Row data-cy={`event-type-${datum.eventType}`} key={datum.id}>
<Cell data-cy={`${datum.eventType}-time`}>
{getDateCopy(datum.timestamp)}
</Cell>
<Cell>
<HostEventString
eventType={datum.eventType}
data={datum.data}
/>
</Cell>
</Row>
)}
</Table>
</V11Adapter>
<BaseTable
data-cy-table="host-events-table"
data-loading={loading}
loading={loading}
loadingRows={limit}
shouldAlternateRowColor
table={table}
/>
</HostCard>
);
};
Expand Down
27 changes: 0 additions & 27 deletions src/utils/request.test.js

This file was deleted.

48 changes: 48 additions & 0 deletions src/utils/request.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { post } from "./request";

describe("post", () => {
afterEach(() => {
jest.clearAllMocks();
});

it("should make a POST request and return the response for a successful request", async () => {
const url = "/api/resource";
const body = { key: "value" };
const fetchMock = jest.fn().mockResolvedValue({
ok: true,
});

jest.spyOn(global, "fetch").mockImplementation(fetchMock);

const response = await post(url, body);

expect(response).toStrictEqual({ ok: true });
expect(fetchMock).toHaveBeenCalledWith("/api/resource", {
method: "POST",
body: JSON.stringify(body),
credentials: "include",
});
});

it("should handle and report an error for a failed request", async () => {
const url = "/api/resource";
const body = { key: "value" };
const fetchMock = jest.fn().mockResolvedValue({
ok: false,
status: 500,
statusText: "Internal Server Error",
});
const errorReportingMock = jest.fn();
jest.spyOn(console, "error").mockImplementation(errorReportingMock);
jest.spyOn(global, "fetch").mockImplementation(fetchMock);

await post(url, body);

expect(fetchMock).toHaveBeenCalledWith("/api/resource", {
method: "POST",
body: JSON.stringify(body),
credentials: "include",
});
expect(errorReportingMock).toHaveBeenCalledTimes(1);
});
});
42 changes: 12 additions & 30 deletions src/utils/request.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,26 @@
import axios from "axios";
import { getUiUrl } from "./environmentVariables";
import { reportError } from "./errorReporting";

type optionsType = {
onFailure?: (e) => void;
};
export const post = async (
url: string,
body: unknown,
options: optionsType = {},
) => {
export const post = async (url: string, body: unknown) => {
try {
const response = await axios.post(
`${getUiUrl()}${url}`,
{ body },
{ withCredentials: true },
);
if (isBadResponse(response)) {
throw new Error(getErrorMessage(response, "POST"));
const response = await fetch(`${getUiUrl()}${url}`, {
method: "POST",
body: JSON.stringify(body),
credentials: "include",
});
if (!response.ok) {
throw new Error(await getErrorMessage(response, "POST"));
}
return response;
} catch (e) {
if (options.onFailure) {
options.onFailure(e);
}
} catch (e: any) {
handleError(e);
}
};

const isBadResponse = (response) =>
!response || (response && response.statusText !== "OK");

type responseType = {
status: number;
statusText: string;
const getErrorMessage = async (response: Response, method: string) => {
const { status, statusText } = response;
return `${method} Error: ${status} - ${statusText}`;
};
const getErrorMessage = (response: responseType, method: string) =>
response
? `${method} Error: ${response.status} - ${response.statusText}`
: `${method} Error: Did not receive a response from the server`;

const handleError = (error: string) => {
reportError(new Error(error)).warning();
Expand Down
11 changes: 1 addition & 10 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -7000,15 +7000,6 @@ axe-core@=4.7.0:
resolved "https://registry.yarnpkg.com/axe-core/-/axe-core-4.7.0.tgz#34ba5a48a8b564f67e103f0aa5768d76e15bbbbf"
integrity sha512-M0JtH+hlOL5pLQwHOLNYZaXuhqmvS8oExsqB1SBYgA4Dk7u/xx+YdGHXaK5pyUfed5mYXdlYiphWq3G8cRi5JQ==

[email protected]:
version "1.6.1"
resolved "https://registry.yarnpkg.com/axios/-/axios-1.6.1.tgz#76550d644bf0a2d469a01f9244db6753208397d7"
integrity sha512-vfBmhDpKafglh0EldBEbVuoe7DyAavGSLWhuSm5ZSEKQnHhBf0xAAwybbNH1IkrJNGnS/VG4I5yxig1pCEXE4g==
dependencies:
follow-redirects "^1.15.0"
form-data "^4.0.0"
proxy-from-env "^1.1.0"

axobject-query@^3.2.1:
version "3.2.1"
resolved "https://registry.yarnpkg.com/axobject-query/-/axobject-query-3.2.1.tgz#39c378a6e3b06ca679f29138151e45b2b32da62a"
Expand Down Expand Up @@ -9674,7 +9665,7 @@ [email protected], focus-trap@^6.9.4:
dependencies:
tabbable "^5.3.3"

follow-redirects@^1.0.0, follow-redirects@^1.15.0:
follow-redirects@^1.0.0:
version "1.15.4"
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.4.tgz#cdc7d308bf6493126b17ea2191ea0ccf3e535adf"
integrity sha512-Cr4D/5wlrb0z9dgERpUL3LrmPKVDsETIJhaCMeDfuFYcqa5bldGV6wBsAN6X/vxlXQtFBMrXdXxdL8CbDTGniw==
Expand Down

0 comments on commit 5e16fbf

Please sign in to comment.