Skip to content

Commit

Permalink
replaced all axios with native fetch and XMLHttpRequest (ohcnetwork#7368
Browse files Browse the repository at this point in the history
)

* replaced all axios with native fetch and XMLHttpRequest

* created a separate util for uploadFile function using XMLHttpRequest

* created a separate reusable function to handle uploadFilePercentage
  • Loading branch information
itxsoumya authored Mar 12, 2024
1 parent a7f82d6 commit 4c51d3a
Show file tree
Hide file tree
Showing 7 changed files with 170 additions and 114 deletions.
16 changes: 12 additions & 4 deletions src/Common/hooks/useMSEplayer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useEffect, useRef } from "react";
import axios from "axios";

export interface IAsset {
middlewareHostname: string;
Expand Down Expand Up @@ -45,9 +44,18 @@ const stopStream =
(payload: { id: string }, options: IOptions) => {
const { id } = payload;
ws?.close();
axios
.post(`https://${middlewareHostname}/stop`, {
id,
fetch(`https://${middlewareHostname}/stop`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ id }),
})
.then((res) => {
if (!res.ok) {
throw new Error("network response was not ok");
}
return res.json();
})
.then((res) => options?.onSuccess && options.onSuccess(res))
.catch((err) => options.onError && options.onError(err));
Expand Down
10 changes: 7 additions & 3 deletions src/Components/Assets/AssetType/ONVIFCamera.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { useEffect, useState } from "react";
import { AssetData, ResolvedMiddleware } from "../AssetTypes";
import * as Notification from "../../../Utils/Notifications.js";
import { BedModel } from "../../Facility/models";
import axios from "axios";
import { getCameraConfig } from "../../../Utils/transformUtils";
import CameraConfigure from "../configure/CameraConfigure";
import Loading from "../../Common/Loading";
Expand Down Expand Up @@ -100,13 +99,18 @@ const ONVIFCamera = ({ assetId, facilityId, asset, onUpdated }: Props) => {
};
try {
setLoadingAddPreset(true);
const presetData = await axios.get(

const response = await fetch(
`https://${resolvedMiddleware?.hostname}/status?hostname=${config.hostname}&port=${config.port}&username=${config.username}&password=${config.password}`
);
if (!response.ok) {
throw new Error("Network error");
}
const presetData = await response.json();

const { res } = await request(routes.createAssetBed, {
body: {
meta: { ...data, ...presetData.data },
meta: { ...data, ...presetData },
asset: assetId,
bed: bed?.id as string,
},
Expand Down
47 changes: 24 additions & 23 deletions src/Components/Facility/CoverImageEditModal.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import axios from "axios";
import {
ChangeEventHandler,
useCallback,
Expand All @@ -20,6 +19,7 @@ import { LocalStorageKeys } from "../../Common/constants";
import DialogModal from "../Common/Dialog";
import request from "../../Utils/request/request";
import routes from "../../Redux/api";
import uploadFile from "../../Utils/request/uploadFile";
interface Props {
open: boolean;
onClose: (() => void) | undefined;
Expand Down Expand Up @@ -105,34 +105,35 @@ const CoverImageEditModal = ({

const formData = new FormData();
formData.append("cover_image", selectedFile);

const url = `/api/v1/facility/${facility.id}/cover_image/`;
setIsUploading(true);
try {
const response = await axios.post(
`/api/v1/facility/${facility.id}/cover_image/`,
formData,
{
headers: {
"Content-Type": "multipart/form-data",
Authorization:
"Bearer " + localStorage.getItem(LocalStorageKeys.accessToken),
},

uploadFile(
url,
formData,
"POST",
{
Authorization:
"Bearer " + localStorage.getItem(LocalStorageKeys.accessToken),
},
(xhr: XMLHttpRequest) => {
if (xhr.status === 200) {
Success({ msg: "Cover image updated." });
} else {
Notification.Error({
msg: "Something went wrong!",
});
setIsUploading(false);
}
);
if (response.status === 200) {
Success({ msg: "Cover image updated." });
} else {
},
null,
() => {
Notification.Error({
msg: "Something went wrong!",
msg: "Network Failure. Please check your internet connectivity.",
});
setIsUploading(false);
}
} catch (e) {
Notification.Error({
msg: "Network Failure. Please check your internet connectivity.",
});
setIsUploading(false);
}
);

await sleep(1000);
setIsUploading(false);
Expand Down
110 changes: 53 additions & 57 deletions src/Components/Patient/FileUpload.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import axios from "axios";
import CircularProgress from "../Common/components/CircularProgress";
import {
useCallback,
Expand Down Expand Up @@ -33,6 +32,7 @@ import useQuery from "../../Utils/request/useQuery";
import routes from "../../Redux/api";
import request from "../../Utils/request/request";
import FilePreviewDialog from "../Common/FilePreviewDialog";
import uploadFile from "../../Utils/request/uploadFile";

const Loading = lazy(() => import("../Common/Loading"));

Expand Down Expand Up @@ -936,42 +936,41 @@ export const FileUpload = (props: FileUploadProps) => {
const f = file;
if (!f) return;
const newFile = new File([f], `${internal_name}`);

const config = {
headers: {
"Content-type": file?.type,
"Content-disposition": "inline",
},
onUploadProgress: (progressEvent: any) => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
setUploadPercent(percentCompleted);
},
};

console.log("filetype: ", newFile.type);
return new Promise<void>((resolve, reject) => {
axios
.put(url, newFile, config)
.then(() => {
setUploadStarted(false);
// setUploadSuccess(true);
setFile(null);
setUploadFileName("");
fetchData();
Notification.Success({
msg: "File Uploaded Successfully",
});
setUploadFileError("");
resolve();
})
.catch((e) => {
uploadFile(
url,
newFile,
"PUT",
{ "Content-Type": file?.type },
(xhr: XMLHttpRequest) => {
if (xhr.status >= 200 && xhr.status < 300) {
setUploadStarted(false);
setFile(null);
setUploadFileName("");
fetchData();
Notification.Success({
msg: "File Uploaded Successfully",
});
setUploadFileError("");
resolve();
} else {
Notification.Error({
msg: "Error Uploading File: " + xhr.statusText,
});
setUploadStarted(false);
reject();
}
},
setUploadPercent,
() => {
Notification.Error({
msg: "Error Uploading File: " + e.message,
msg: "Error Uploading File: Network Error",
});
setUploadStarted(false);
reject();
});
}
);
});
};

Expand Down Expand Up @@ -1049,33 +1048,30 @@ export const FileUpload = (props: FileUploadProps) => {
const f = audioBlob;
if (f === undefined) return;
const newFile = new File([f], `${internal_name}`, { type: f.type });
const config = {
headers: {
"Content-type": newFile?.type,
"Content-disposition": "inline",
},
onUploadProgress: (progressEvent: any) => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
setUploadPercent(percentCompleted);
},
};

axios
.put(url, newFile, config)
.then(() => {
setAudioUploadStarted(false);
// setUploadSuccess(true);
setAudioName("");
fetchData();
Notification.Success({
msg: "File Uploaded Successfully",
});
})
.catch(() => {
uploadFile(
url,
newFile,
"PUT",
{ "Content-Type": newFile?.type },
(xhr: XMLHttpRequest) => {
if (xhr.status >= 200 && xhr.status < 300) {
setAudioUploadStarted(false);
// setUploadSuccess(true);
setAudioName("");
fetchData();
Notification.Success({
msg: "File Uploaded Successfully",
});
} else {
setAudioUploadStarted(false);
}
},
setUploadPercent,
() => {
setAudioUploadStarted(false);
});
}
);
};

const validateAudioUpload = () => {
Expand Down
54 changes: 27 additions & 27 deletions src/Components/Patient/UpdateStatusDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useEffect, useState, useReducer } from "react";
import axios from "axios";
import {
SAMPLE_TEST_STATUS,
SAMPLE_TEST_RESULT,
Expand All @@ -18,6 +17,7 @@ import CheckBoxFormField from "../Form/FormFields/CheckBoxFormField";
import { useTranslation } from "react-i18next";
import request from "../../Utils/request/request";
import routes from "../../Redux/api";
import uploadFile from "../../Utils/request/uploadFile";

interface Props {
sample: SampleTestModel;
Expand Down Expand Up @@ -104,36 +104,36 @@ const UpdateStatusDialog = (props: Props) => {
if (f === undefined) return;
const newFile = new File([f], `${internal_name}`);

const config = {
headers: {
"Content-type": contentType,
uploadFile(
url,
newFile,
"PUT",
{
"Content-Type": contentType,
"Content-disposition": "inline",
},
onUploadProgress: (progressEvent: any) => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
setUploadPercent(percentCompleted);
(xhr: XMLHttpRequest) => {
if (xhr.status >= 200 && xhr.status < 300) {
setUploadStarted(false);
setUploadDone(true);
request(routes.editUpload, {
pathParams: {
id: data.id,
fileType: "SAMPLE_MANAGEMENT",
associatingId: sample.id?.toString() ?? "",
},
body: { upload_completed: true },
});
Notification.Success({ msg: "File Uploaded Successfully" });
} else {
setUploadStarted(false);
}
},
};

axios
.put(url, newFile, config)
.then(() => {
setUploadPercent,
() => {
setUploadStarted(false);
setUploadDone(true);
request(routes.editUpload, {
pathParams: {
id: data.id,
fileType: "SAMPLE_MANAGEMENT",
associatingId: sample.id?.toString() ?? "",
},
body: { upload_completed: true },
});

Notification.Success({ msg: "File Uploaded Successfully" });
})
.catch(() => setUploadStarted(false));
}
);
};

const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
Expand Down
36 changes: 36 additions & 0 deletions src/Utils/request/uploadFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Dispatch, SetStateAction } from "react";
import { handleUploadPercentage } from "./utils";

const uploadFile = (
url: string,
file: File | FormData,
reqMethod: string,
headers: object,
onLoad: (xhr: XMLHttpRequest) => void,
setUploadPercent: Dispatch<SetStateAction<number>> | null,
onError: () => void
) => {
const xhr = new XMLHttpRequest();
xhr.open(reqMethod, url);

Object.entries(headers).forEach(([key, value]) => {
xhr.setRequestHeader(key, value);
});

xhr.onload = () => {
onLoad(xhr);
};

if (setUploadPercent != null) {
xhr.upload.onprogress = (event: ProgressEvent) => {
handleUploadPercentage(event, setUploadPercent);
};
}

xhr.onerror = () => {
onError();
};
xhr.send(file);
};

export default uploadFile;
Loading

0 comments on commit 4c51d3a

Please sign in to comment.