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

Replace Deprecated request #10352

Open
wants to merge 9 commits into
base: develop
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions public/locale/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,7 @@
"delete_record": "Delete Record",
"deleted_successfully": "{{name}} deleted successfully",
"deleting": "Deleting...",
"deletion_failed": "Failed to delete {{name}}",
"demography": "Demography",
"denied_on": "Denied On",
"departments": "Departments",
Expand Down
36 changes: 19 additions & 17 deletions src/Providers/AuthUserProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ import { AuthUserContext } from "@/hooks/useAuthUser";
import { LocalStorageKeys } from "@/common/constants";

import routes from "@/Utils/request/api";
import query from "@/Utils/request/query";
import request from "@/Utils/request/request";
import query, { callApi } from "@/Utils/request/query";
import { TokenData } from "@/types/auth/otpToken";

interface Props {
Expand Down Expand Up @@ -56,12 +55,12 @@ export default function AuthUserProvider({

const signIn = useCallback(
async (creds: { username: string; password: string }) => {
const query = await request(routes.login, { body: creds });
const data = await callApi(routes.login, { body: creds });

if (query.res?.ok && query.data) {
setAccessToken(query.data.access);
localStorage.setItem(LocalStorageKeys.accessToken, query.data.access);
localStorage.setItem(LocalStorageKeys.refreshToken, query.data.refresh);
if (data?.access && data?.refresh) {
setAccessToken(data.access);
localStorage.setItem(LocalStorageKeys.accessToken, data.access);
localStorage.setItem(LocalStorageKeys.refreshToken, data.refresh);

await queryClient.invalidateQueries({ queryKey: ["currentUser"] });

Expand All @@ -70,7 +69,7 @@ export default function AuthUserProvider({
}
}

return query;
return data;
},
[queryClient],
);
Expand Down Expand Up @@ -155,19 +154,22 @@ const updateRefreshToken = async (silent = false) => {
return;
}

const { res, data } = await request(routes.token_refresh, {
body: { refresh },
silent,
});
try {
const data = await callApi(routes.token_refresh, {
body: { refresh },
silent,
});

if (!data) {
throw new Error("Token refresh failed");
}

if (res?.status !== 200 || !data) {
localStorage.setItem(LocalStorageKeys.accessToken, data.access);
localStorage.setItem(LocalStorageKeys.refreshToken, data.refresh);
} catch {
localStorage.removeItem(LocalStorageKeys.accessToken);
localStorage.removeItem(LocalStorageKeys.refreshToken);
return;
}

localStorage.setItem(LocalStorageKeys.accessToken, data.access);
localStorage.setItem(LocalStorageKeys.refreshToken, data.refresh);
};

const getRedirectURL = () => {
Expand Down
2 changes: 2 additions & 0 deletions src/Utils/request/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { ApiCallOptions, ApiRoute, HTTPError } from "@/Utils/request/types";
import { makeHeaders, makeUrl } from "@/Utils/request/utils";
import { sleep } from "@/Utils/utils";

export type ApiResponse<TData> = TData;

export async function callApi<Route extends ApiRoute<unknown, unknown>>(
{ path, method, noAuth }: Route,
options?: ApiCallOptions<Route>,
Expand Down
15 changes: 4 additions & 11 deletions src/components/Auth/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ import FiltersCache from "@/Utils/FiltersCache";
import ViewCache from "@/Utils/ViewCache";
import routes from "@/Utils/request/api";
import mutate from "@/Utils/request/mutate";
import request from "@/Utils/request/request";
import { TokenData } from "@/types/auth/otpToken";

interface LoginFormData {
Expand Down Expand Up @@ -103,20 +102,14 @@ const Login = (props: LoginProps) => {
FiltersCache.invaldiateAll();
return await signIn(data);
},
onSuccess: ({ res }) => {
setCaptcha(res?.status === 429);
onSuccess: (res) => {
setCaptcha(!!res?.access);
},
});

// Send OTP Mutation
const { mutate: sendOtp, isPending: sendOtpPending } = useMutation({
mutationFn: async (phone: string) => {
const response = await request(routes.otp.sendOtp, {
body: { phone_number: phone },
silent: true,
});
return response;
},
mutationFn: mutate(routes.otp.sendOtp),
onSuccess: () => {
setIsOtpSent(true);
setOtpError("");
Expand Down Expand Up @@ -280,7 +273,7 @@ const Login = (props: LoginProps) => {

try {
if (!isOtpSent) {
await sendOtp(phone);
await sendOtp({ phone_number: phone });
setIsOtpSent(true);
} else {
await verifyOtp({ phone_number: phone, otp });
Expand Down
28 changes: 17 additions & 11 deletions src/components/Auth/ResetPassword.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { LocalStorageKeys } from "@/common/constants";
import { validatePassword } from "@/common/validation";

import routes from "@/Utils/request/api";
import request from "@/Utils/request/request";
import { callApi } from "@/Utils/request/query";

interface ResetPasswordProps {
token: string;
Expand Down Expand Up @@ -75,28 +75,34 @@ const ResetPassword = (props: ResetPasswordProps) => {
const valid = validateData();
if (valid) {
valid.token = props.token;
const { res, error } = await request(routes.resetPassword, {
body: { ...valid },
});
if (res?.ok) {

try {
await callApi(routes.resetPassword, {
body: { ...valid },
});

localStorage.removeItem(LocalStorageKeys.accessToken);
toast.success(t("password_reset_success"));
navigate("/login");
} else if (res && error) {
setErrors(error);
} catch (error: any) {
if (error.cause) {
setErrors(error.cause);
}
}
}
};

useEffect(() => {
const checkResetToken = async () => {
const { res } = await request(routes.checkResetToken, {
body: { token: props.token },
});
if (!res || !res.ok) {
try {
await callApi(routes.checkResetToken, {
body: { token: props.token },
});
} catch {
navigate("/invalid-reset");
}
};

if (props.token) {
checkResetToken();
} else {
Expand Down
34 changes: 17 additions & 17 deletions src/components/Facility/FacilityHome.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ import { FACILITY_FEATURE_TYPES } from "@/common/constants";

import { PLUGIN_Component } from "@/PluginEngine";
import routes from "@/Utils/request/api";
import query from "@/Utils/request/query";
import request from "@/Utils/request/request";
import query, { callApi } from "@/Utils/request/query";
import uploadFile from "@/Utils/request/uploadFile";
import { getAuthorizationHeader } from "@/Utils/request/utils";
import { sleep } from "@/Utils/utils";
Expand Down Expand Up @@ -111,17 +110,17 @@ export const FacilityHome = ({ facilityId }: Props) => {
};

const handleDeleteSubmit = async () => {
await request(routes.deleteFacility, {
pathParams: { id: facilityId },
onResponse: ({ res }) => {
if (res?.ok) {
toast.success(
t("deleted_successfully", { name: facilityData?.name }),
);
}
try {
const res = await callApi(routes.deleteFacility, {
pathParams: { id: facilityId },
});
if (res) {
toast.success(t("deleted_successfully", { name: facilityData?.name }));
navigate("/facility");
},
});
}
} catch (_error) {
toast.error(t("delete_failed", { name: facilityData?.name }));
}
};

const handleCoverImageUpload = async (file: File, onError: () => void) => {
Expand Down Expand Up @@ -154,16 +153,17 @@ export const FacilityHome = ({ facilityId }: Props) => {
};

const handleCoverImageDelete = async (onError: () => void) => {
const { res } = await request(routes.deleteFacilityCoverImage, {
pathParams: { id: facilityId },
});
if (res?.ok) {
try {
await callApi(routes.deleteFacilityCoverImage, {
pathParams: { id: facilityId },
});

toast.success(t("cover_image_deleted"));
queryClient.invalidateQueries({
queryKey: ["facility", facilityId],
});
setEditCoverImage(false);
} else {
} catch {
onError();
}
};
Expand Down
18 changes: 9 additions & 9 deletions src/components/Resource/ResourceCommentSection.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useMutation } from "@tanstack/react-query";
import { t } from "i18next";
import { useState } from "react";
import { toast } from "sonner";
Expand All @@ -11,13 +12,18 @@ import { Avatar } from "@/components/Common/Avatar";
import CircularProgress from "@/components/Common/CircularProgress";

import routes from "@/Utils/request/api";
import request from "@/Utils/request/request";
import mutate from "@/Utils/request/mutate";
import { formatName, relativeTime } from "@/Utils/utils";
import { CommentModel } from "@/types/resourceRequest/resourceRequest";

const CommentSection = (props: { id: string }) => {
const [commentBox, setCommentBox] = useState("");

const { mutate: addResourceComments } = useMutation({
mutationFn: mutate(routes.addResourceComments, {
pathParams: { id: props.id },
}),
onSuccess: () => toast.success(t("comment_added_successfully")),
});
AdityaJ2305 marked this conversation as resolved.
Show resolved Hide resolved
const onSubmitComment = async () => {
const payload = {
comment: commentBox,
Expand All @@ -26,13 +32,7 @@ const CommentSection = (props: { id: string }) => {
toast.error(t("comment_min_length"));
return;
}
const { res } = await request(routes.addResourceComments, {
pathParams: { id: props.id },
body: payload,
});
if (res?.ok) {
toast.success(t("comment_added_successfully"));
}
addResourceComments(payload);
setCommentBox("");
};
return (
Expand Down
Loading
Loading