Skip to content

Commit

Permalink
chore(types) add return type to all util functions
Browse files Browse the repository at this point in the history
Signed-off-by: David Edler <david.edler@canonical.com>
  • Loading branch information
edlerd committed Feb 16, 2024
1 parent d6d00bc commit fb0212b
Show file tree
Hide file tree
Showing 27 changed files with 109 additions and 107 deletions.
8 changes: 6 additions & 2 deletions src/util/clusterGroups.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { LxdClusterMember } from "types/cluster";
import EvacuateClusterMemberBtn from "pages/cluster/actions/EvacuateClusterMemberBtn";
import RestoreClusterMemberBtn from "pages/cluster/actions/RestoreClusterMemberBtn";
import {
MainTableHeader,
MainTableRow,
} from "@canonical/react-components/dist/components/MainTable/MainTable";

export const allClusterGroups = "All cluster groups";

export const getClusterHeaders = (activeGroup?: string) => [
export const getClusterHeaders = (activeGroup?: string): MainTableHeader[] => [
{
content: (
<>
Expand Down Expand Up @@ -44,7 +48,7 @@ export const getClusterHeaders = (activeGroup?: string) => [
export const getClusterRows = (
members: LxdClusterMember[],
activeGroup?: string,
) =>
): MainTableRow[] =>
members.map((member) => {
return {
className: "u-row",
Expand Down
2 changes: 1 addition & 1 deletion src/util/config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const configDescriptionToHtml = (
input: string,
docBaseLink: string,
objectsInvTxt?: string[],
) => {
): string => {
// special characters
let result = input
.replaceAll("<", "&lt;")
Expand Down
2 changes: 1 addition & 1 deletion src/util/cookies.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export const getCookie = (key: string) => {
export const getCookie = (key: string): string | undefined => {
const val = document.cookie.match(`(^|;)\\s*${key}\\s*=\\s*([^;]+)`);
return val ? val.pop() : undefined;
};
4 changes: 2 additions & 2 deletions src/util/formDevices.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export interface FormDeviceValues {
devices: FormDevice[];
}

export const isEmptyDevice = (device: FormDevice) =>
export const isEmptyDevice = (device: FormDevice): boolean =>
device.type === "nic" &&
device.name.length === 0 &&
(device.network?.length ?? 0) === 0;
Expand Down Expand Up @@ -174,7 +174,7 @@ export const remoteImageToIsoDevice = (image: RemoteImage): FormDevice => {
export const removeDevice = (
index: number,
formik: InstanceAndProfileFormikProps,
) => {
): void => {
const copy = [...formik.values.devices];
copy.splice(index, 1);
void formik.setFieldValue("devices", copy);
Expand Down
71 changes: 25 additions & 46 deletions src/util/helpers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { Dispatch, SetStateAction } from "react";

export const UNDEFINED_DATE = "0001-01-01T00:00:00Z";

export const isoTimeToString = (isoTime: string) => {
export const isoTimeToString = (isoTime: string): string => {
if (isoTime === UNDEFINED_DATE) {
return "";
}
Expand All @@ -28,12 +28,12 @@ export const isoTimeToString = (isoTime: string) => {
});
};

export const stringToIsoTime = (dateTime: string) => {
export const stringToIsoTime = (dateTime: string): string => {
const date = new Date(dateTime);
return date.toISOString();
};

export const getTomorrow = (date: Date = new Date()) => {
export const getTomorrow = (date: Date = new Date()): string => {
// set date as next day
date.setDate(date.getDate() + 1);
// set time to midnight
Expand All @@ -44,9 +44,9 @@ export const getTomorrow = (date: Date = new Date()) => {
return new Date(date.getTime() - tzOffset).toISOString().slice(0, 10);
};

const pad = (v: number) => `0${v}`.slice(-2);
const pad = (v: number): string => `0${v}`.slice(-2);

export const getBrowserFormatDate = (d: Date) =>
export const getBrowserFormatDate = (d: Date): string =>
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(
d.getHours(),
)}:${pad(d.getMinutes())}`;
Expand Down Expand Up @@ -74,7 +74,7 @@ export const handleResponse = async (response: Response) => {

export const handleSettledResult = (
results: PromiseSettledResult<unknown>[],
) => {
): void => {
const error = (
results.find((res) => res.status === "rejected") as
| PromiseRejectedResult
Expand All @@ -95,7 +95,9 @@ export const handleEtagResponse = async (response: Response) => {
return result;
};

export const handleTextResponse = async (response: Response) => {
export const handleTextResponse = async (
response: Response,
): Promise<string> => {
if (!response.ok) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const result: ErrorResponse = await response.json();
Expand All @@ -104,7 +106,7 @@ export const handleTextResponse = async (response: Response) => {
return response.text();
};

export const humanFileSize = (bytes: number, toBibyte = false) => {
export const humanFileSize = (bytes: number, toBibyte = false): string => {
if (Math.abs(bytes) < 1000) {
return `${bytes} B`;
}
Expand All @@ -125,7 +127,7 @@ export const humanFileSize = (bytes: number, toBibyte = false) => {
return `${bytes.toFixed(1)} ${units[u]}`;
};

export const getWsErrorMsg = (code: number) => {
export const getWsErrorMsg = (code: number): string => {
// See https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1
if (code == 1000)
return "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
Expand Down Expand Up @@ -186,12 +188,15 @@ export const getUrlParam = (paramName: string, url?: string): string | null => {
return browserUrl.searchParams.get(paramName);
};

export const defaultFirst = (p1: { name: string }, p2: { name: string }) =>
p1.name === "default" ? -1 : p2.name === "default" ? 1 : 0;
export const defaultFirst = (
p1: { name: string },
p2: { name: string },
): number => (p1.name === "default" ? -1 : p2.name === "default" ? 1 : 0);

export const isWidthBelow = (width: number) => window.innerWidth < width;
export const isWidthBelow = (width: number): boolean =>
window.innerWidth < width;

export const getParentsBottomSpacing = (element: Element) => {
export const getParentsBottomSpacing = (element: Element): number => {
let sum = 0;
while (element.parentElement) {
element = element.parentElement;
Expand All @@ -205,7 +210,7 @@ export const getParentsBottomSpacing = (element: Element) => {

export const getPromiseSettledCounts = (
results: PromiseSettledResult<void>[],
) => {
): { fulfilledCount: number; rejectedCount: number } => {
const fulfilledCount = results.filter(
(result) => result.status === "fulfilled",
).length;
Expand All @@ -215,7 +220,7 @@ export const getPromiseSettledCounts = (
return { fulfilledCount, rejectedCount };
};

export const pushSuccess = (results: PromiseSettledResult<void>[]) => {
export const pushSuccess = (results: PromiseSettledResult<void>[]): void => {
results.push({
status: "fulfilled",
value: undefined,
Expand All @@ -225,7 +230,7 @@ export const pushSuccess = (results: PromiseSettledResult<void>[]) => {
export const pushFailure = (
results: PromiseSettledResult<void>[],
msg: string,
) => {
): void => {
results.push({
status: "rejected",
reason: msg,
Expand All @@ -236,19 +241,19 @@ export const continueOrFinish = (
results: PromiseSettledResult<void>[],
totalLength: number,
resolve: (value: PromiseSettledResult<void>[]) => void,
) => {
): void => {
if (totalLength === results.length) {
resolve(results);
}
};

export const logout = () =>
export const logout = (): void =>
void fetch("/oidc/logout").then(() => window.location.reload());

export const capitalizeFirstLetter = (val: string) =>
export const capitalizeFirstLetter = (val: string): string =>
val.charAt(0).toUpperCase() + val.slice(1);

export const getAbsoluteHeightBelow = (belowId: string) => {
export const getAbsoluteHeightBelow = (belowId: string): number => {
const element = belowId ? document.getElementById(belowId) : undefined;
if (!element) {
return 0;
Expand All @@ -259,29 +264,3 @@ export const getAbsoluteHeightBelow = (belowId: string) => {
parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
return element.offsetHeight + margin + padding + 1;
};

export const getElementAbsoluteHeight = (element: HTMLElement | null) => {
if (!element) {
return 0;
}

const style = window.getComputedStyle(element);
const marginHeight =
parseFloat(style.marginTop) + parseFloat(style.marginBottom);
return element.offsetHeight + marginHeight;
};

export const getNegativeMargin = (element: HTMLElement | null) => {
if (!element) {
return 0;
}

const style = window.getComputedStyle(element);
const marginHeight =
parseFloat(style.marginTop) + parseFloat(style.marginBottom);
return marginHeight < 0 ? marginHeight : 0;
};

export const getHeightOffsetStyle = (offset: number) => {
return `height: calc(100vh - ${offset}px); min-height: calc(100vh - ${offset}px)`;
};
6 changes: 3 additions & 3 deletions src/util/images.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { LxdImage, RemoteImage } from "types/image";
import { LxdStorageVolume } from "types/storage";

export const isVmOnlyImage = (image: RemoteImage) => {
export const isVmOnlyImage = (image: RemoteImage): boolean | undefined => {
if (image.server === LOCAL_ISO) {
return true;
}
return image.variant?.includes("desktop");
};

export const isContainerOnlyImage = (image: RemoteImage) => {
export const isContainerOnlyImage = (image: RemoteImage): boolean => {
if (isVmOnlyImage(image)) {
return false;
}
Expand Down Expand Up @@ -50,7 +50,7 @@ export const localLxdToRemoteImage = (image: LxdImage): RemoteImage => {
};
};

export const byLtsFirst = (a: RemoteImage, b: RemoteImage) => {
export const byLtsFirst = (a: RemoteImage, b: RemoteImage): number => {
if (a.aliases.includes("lts")) {
return -1;
}
Expand Down
8 changes: 4 additions & 4 deletions src/util/instanceBulkActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,19 @@ export const instanceActionLabel = (action: LxdInstanceAction): string => {
}[action];
};

export const pluralizeInstance = (count: number) => {
export const pluralizeInstance = (count: number): string => {
return pluralize("instance", count);
};

export const pluralizeSnapshot = (count: number) => {
export const pluralizeSnapshot = (count: number): string => {
return pluralize("snapshot", count);
};

export const pluralize = (item: string, count: number) => {
export const pluralize = (item: string, count: number): string => {
return count === 1 ? item : `${item}s`;
};

export const statusLabel = (status: LxdInstanceStatus) => {
export const statusLabel = (status: LxdInstanceStatus): string | undefined => {
const statusToLabel: Partial<Record<LxdInstanceStatus, string>> = {
Frozen: "frozen",
Stopped: "stopped",
Expand Down
4 changes: 2 additions & 2 deletions src/util/instanceConfigFields.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const instanceConfigFormFieldsToPayload: Record<string, string> = {
cloud_init_vendor_data: "cloud-init.vendor-data",
};

export const getInstanceKey = (formField: string) => {
export const getInstanceKey = (formField: string): string => {
if (!(formField in instanceConfigFormFieldsToPayload)) {
throw new Error(
`Could not find ${formField} in instanceConfigFormFieldsToPayload`,
Expand All @@ -32,7 +32,7 @@ export const getInstanceKey = (formField: string) => {
return instanceConfigFormFieldsToPayload[formField];
};

const getConfigKeys = () => {
const getConfigKeys = (): Set<string> => {
return new Set(Object.values(instanceConfigFormFieldsToPayload));
};

Expand Down
9 changes: 7 additions & 2 deletions src/util/instanceEdit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import { EditInstanceFormValues } from "pages/instances/EditInstance";
import * as Yup from "yup";
import { EditProfileFormValues } from "pages/profiles/EditProfile";

const getEditValues = (item: LxdProfile | LxdInstance) => {
const getEditValues = (
item: LxdProfile | LxdInstance,
): Omit<EditProfileFormValues, "entityType" | "readOnly"> => {
return {
name: item.name,
description: item.description,
Expand Down Expand Up @@ -104,7 +106,10 @@ export const getInstancePayload = (
};
};

export const InstanceEditSchema = Yup.object().shape({
export const InstanceEditSchema: Yup.ObjectSchema<{
name: string;
instanceType: string;
}> = Yup.object().shape({
name: Yup.string().required("Instance name is required"),
instanceType: Yup.string().required("Instance type is required"),
});
4 changes: 3 additions & 1 deletion src/util/instanceFilter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ export const instanceStatuses: LxdInstanceStatus[] = [

export const instanceTypes: string[] = ["Container", "VM"];

export const enrichStatuses = (statuses: LxdInstanceStatus[]) => {
export const enrichStatuses = (
statuses: LxdInstanceStatus[],
): LxdInstanceStatus[] => {
if (statuses.includes("Frozen")) {
statuses.push("Freezing");
}
Expand Down
2 changes: 1 addition & 1 deletion src/util/instanceSnapshots.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as Yup from "yup";
import { testFutureDate, testValidDate, testValidTime } from "./snapshots";

/*** Instance snapshot utils ***/
export const isInstanceStateful = (instance: LxdInstance) => {
export const isInstanceStateful = (instance: LxdInstance): boolean => {
return Boolean(instance.config["migration.stateful"]);
};

Expand Down
12 changes: 7 additions & 5 deletions src/util/instanceValidation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,27 @@ import { FormikTouched } from "formik";
export const hasNoRootDisk = (
values: InstanceAndProfileFormValues & { profiles?: string[] },
profiles: LxdProfile[],
) => {
): boolean => {
if (values.entityType !== "instance") {
return false;
}
return missingRoot(values.devices) && !inheritsRoot(values, profiles);
};

const missingRoot = (devices: FormDevice[]) => {
const missingRoot = (devices: FormDevice[]): boolean => {
return !devices.some((item) => item.type === "disk" && item.name === "root");
};

const inheritsRoot = (
values: InstanceAndProfileFormValues,
profiles: LxdProfile[],
) => {
): boolean => {
const [inheritValue] = getInheritedRootStorage(values, profiles);

return !!inheritValue;
};

export const hasDiskError = (formik: InstanceAndProfileFormikProps) =>
export const hasDiskError = (formik: InstanceAndProfileFormikProps): boolean =>
!formik.values.yaml &&
formik.values.devices.some((_device, index) =>
isDiskDeviceMountPointMissing(formik, index),
Expand All @@ -53,7 +53,9 @@ export const isDiskDeviceMountPointMissing = (
return Boolean(hasTouched) && formDevice.path.length < 1;
};

export const hasNetworkError = (formik: InstanceAndProfileFormikProps) =>
export const hasNetworkError = (
formik: InstanceAndProfileFormikProps,
): boolean =>
!formik.values.yaml &&
formik.values.devices.some((_device, index) =>
isNicDeviceNameMissing(formik, index),
Expand Down
Loading

0 comments on commit fb0212b

Please sign in to comment.