refactor: update axios client import, enhance device and payment handling, and add cancel payment button component
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 6m28s

This commit is contained in:
i701 2025-04-08 21:37:51 +05:00
parent daab793592
commit 7e49bf119a
Signed by: i701
GPG Key ID: 54A0DA1E26D8E587
14 changed files with 270 additions and 178 deletions

View File

@ -24,7 +24,6 @@ export async function createPayment(data: NewPayment) {
body: JSON.stringify(data), body: JSON.stringify(data),
}, },
); );
if (!response.ok) { if (!response.ok) {
const errorData = await response.json(); const errorData = await response.json();
// Throw an error with the message from the API // Throw an error with the message from the API
@ -32,7 +31,7 @@ export async function createPayment(data: NewPayment) {
} }
const payment = (await response.json()) as Payment; const payment = (await response.json()) as Payment;
revalidatePath("/devices"); revalidatePath("/devices");
redirect(`/payments/${payment.id}`); return payment;
} }
export async function getPayment({ id }: { id: string }) { export async function getPayment({ id }: { id: string }) {
@ -48,8 +47,13 @@ export async function getPayment({ id }: { id: string }) {
}, },
); );
if (response.status === 404) {
throw new Error("Payment not found");
}
if (!response.ok) { if (!response.ok) {
const errorData = await response.json(); const errorData = await response.json();
console.log(errorData);
// Throw an error with the message from the API // Throw an error with the message from the API
throw new Error(errorData.message || "Something went wrong."); throw new Error(errorData.message || "Something went wrong.");
} }
@ -59,7 +63,7 @@ export async function getPayment({ id }: { id: string }) {
export async function getPayments() { export async function getPayments() {
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
const respose = await fetch( const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/`, `${process.env.SARLINK_API_BASE_URL}/api/billing/payment/`,
{ {
method: "GET", method: "GET",
@ -69,10 +73,35 @@ export async function getPayments() {
}, },
}, },
); );
const data = (await respose.json()) as ApiResponse<Payment>; console.log("response statys", response.status);
if (response.status === 401) {
// Redirect to the signin page if the user is unauthorized
throw new Error("Unauthorized; redirect to /auth/signin");
}
const data = (await response.json()) as ApiResponse<Payment>;
return data; return data;
} }
export async function cancelPayment({ id }: { id: string }) {
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/${id}/delete/`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
},
);
if (response.status === 401) {
// Redirect to the signin page if the user is unauthorized
throw new Error("Unauthorized; redirect to /auth/signin");
}
// Since the response is 204 No Content, there's no JSON to parse
return { message: "Payment successfully canceled." };
}
type UpdatePayment = Pick< type UpdatePayment = Pick<
Payment, Payment,
"id" | "paid" | "paid_at" | "method" | "number_of_months" "id" | "paid" | "paid_at" | "method" | "number_of_months"

View File

@ -1,11 +1,12 @@
import { getPayment } from "@/actions/payment"; import { getPayment } from "@/actions/payment";
import { authOptions } from "@/app/auth"; import { authOptions } from "@/app/auth";
import CancelPaymentButton from "@/components/billing/cancel-payment-button";
import DevicesToPay from "@/components/devices-to-pay"; import DevicesToPay from "@/components/devices-to-pay";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { tryCatch } from "@/utils/tryCatch"; import { tryCatch } from "@/utils/tryCatch";
import { Trash2 } from "lucide-react";
import { getServerSession } from "next-auth"; import { getServerSession } from "next-auth";
import { headers } from "next/headers";
import React from "react";
export default async function PaymentPage({ export default async function PaymentPage({
params, params,
}: { }: {
@ -16,22 +17,25 @@ export default async function PaymentPage({
const paymentId = (await params).paymentId; const paymentId = (await params).paymentId;
const [error, payment] = await tryCatch(getPayment({ id: paymentId })); const [error, payment] = await tryCatch(getPayment({ id: paymentId }));
if (error) { if (error) {
return <div>Error getting payment: {error.message}</div>; return <span>Error getting payment: {error.message}</span>;
} }
return ( return (
<div> <div>
<div className="flex justify-between items-center border-[1px] rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4"> <div className="flex justify-between items-center border-[1px] rounded-md border-dashed font-bold title-bg py-4 px-4 mb-4 mx-2">
<h3 className="text-sarLinkOrange text-2xl">Payment</h3> <h3 className="text-sarLinkOrange text-2xl">Payment</h3>
<span <div className="flex gap-4 items-center">
className={cn( <span
"text-sm border px-4 py-2 rounded-md uppercase font-semibold", className={cn(
payment?.paid "text-sm border px-4 py-2 rounded-md uppercase font-semibold",
? "text-green-500 bg-green-500/20" payment?.paid
: "text-yellow-500 bg-yellow-700", ? "text-green-500 bg-green-500/20"
)} : "text-yellow-500 bg-yellow-700",
> )}
{payment?.paid ? "Paid" : "Pending"} >
</span> {payment?.paid ? "Paid" : "Pending"}
</span>
<CancelPaymentButton paymentId={paymentId} />
</div>
</div> </div>
<div <div

View File

@ -3,33 +3,31 @@ import Search from "@/components/search";
import { Suspense } from "react"; import { Suspense } from "react";
export default async function Devices({ export default async function Devices({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ searchParams: Promise<{
query: string; query: string;
page: number; page: number;
sortBy: string; sortBy: string;
status: string; status: string;
}>; }>;
}) { }) {
const query = (await searchParams)?.query || ""; const query = (await searchParams)?.query || "";
return ( return (
<div> <div>
<div className="flex justify-between items-center border-[1px] rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4"> <div className="flex justify-between items-center border-[1px] rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl"> <h3 className="text-sarLinkOrange text-2xl">My Payments</h3>
My Payments </div>
</h3>
</div>
<div <div
id="user-filters" id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start" className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
> >
<Search /> <Search />
</div> </div>
<Suspense key={query} fallback={"loading...."}> <Suspense key={query} fallback={"loading...."}>
<PaymentsTable searchParams={searchParams} /> <PaymentsTable searchParams={searchParams} />
</Suspense> </Suspense>
</div> </div>
); );
} }

View File

@ -10,6 +10,9 @@ export default function AddDevicesToCartButton({ device }: { device: Device }) {
const isChecked = devices.some((d) => d.id === device.id); const isChecked = devices.some((d) => d.id === device.id);
if (device.has_a_pending_payment || device.is_active) {
return null;
}
return ( return (
<input <input
type="checkbox" type="checkbox"

View File

@ -0,0 +1,35 @@
"use client";
import { cancelPayment } from "@/actions/payment";
import { tryCatch } from "@/utils/tryCatch";
import { Loader2, Trash2 } from "lucide-react";
import { useRouter } from "next/navigation";
import React from "react";
import { toast } from "sonner";
import { Button } from "../ui/button";
export default function CancelPaymentButton({
paymentId,
}: { paymentId: string }) {
const router = useRouter();
const [loading, setLoading] = React.useState(false);
return (
<Button
onClick={async () => {
setLoading(true);
const [error, _] = await tryCatch(cancelPayment({ id: paymentId }));
if (error) {
toast.error(error.message);
setLoading(false);
} else {
router.replace("/devices");
}
}}
disabled={loading}
variant={"destructive"}
>
Cancel Payment
{loading ? <Loader2 className="animate-spin" /> : <Trash2 />}
</Button>
);
}

View File

@ -5,6 +5,7 @@ import type { Device } from "@/lib/backend-types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { pl } from "date-fns/locale"; import { pl } from "date-fns/locale";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import { Hourglass } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import AddDevicesToCartButton from "./add-devices-to-cart-button"; import AddDevicesToCartButton from "./add-devices-to-cart-button";
import BlockDeviceDialog from "./block-device-dialog"; import BlockDeviceDialog from "./block-device-dialog";
@ -20,12 +21,13 @@ export default function ClickableRow({
key={device.id} key={device.id}
className={cn( className={cn(
(parentalControl === false && device.blocked) || device.is_active (parentalControl === false && device.blocked) || device.is_active
? "cursor-not-allowed title-bg" ? "cursor-not-allowed bg-accent-foreground/10 hover:bg-accent-foreground/10"
: "cursor-pointer hover:bg-muted", : "cursor-pointer hover:bg-muted",
)} )}
onClick={() => { onClick={() => {
if (device.blocked) return; if (device.blocked) return;
if (device.is_active === true) return; if (device.is_active === true) return;
if (device.has_a_pending_payment === true) return;
if (parentalControl === true) return; if (parentalControl === true) return;
setDeviceCart((prev) => setDeviceCart((prev) =>
devices.some((d) => d.id === device.id) devices.some((d) => d.id === device.id)
@ -47,22 +49,34 @@ export default function ClickableRow({
{device.name} {device.name}
</Link> </Link>
{device.is_active ? ( {device.is_active ? (
<span className="text-muted-foreground"> <div className="text-muted-foreground">
Active until{" "} Active until{" "}
{new Date(device.expiry_date || "").toLocaleDateString("en-US", { <span className="font-semibold">
month: "short", {new Date(device.expiry_date || "").toLocaleDateString(
day: "2-digit", "en-US",
year: "numeric", {
})} month: "short",
</span> day: "2-digit",
year: "numeric",
},
)}
</span>
</div>
) : ( ) : (
<p className="text-muted-foreground">Device Inactive</p> <p className="text-muted-foreground">Device Inactive</p>
)} )}
{device.has_a_pending_payment && (
<Link href={`/payments/${device.pending_payment_id}`}>
<span className="flex hover:underline items-center justify-center gap-2 text-muted-foreground text-yellow-600">
Payment Pending <Hourglass size={14} />
</span>
</Link>
)}
{device.blocked_by === "ADMIN" && device.blocked && ( {device.blocked_by === "ADMIN" && device.blocked && (
<div className="p-2 rounded border my-2"> <div className="p-2 rounded border my-2 bg-white dark:bg-neutral-800 shadow">
<span>Comment: </span> <span className="font-semibold">Comment</span>
<p className="text-neutral-500">{device?.reason_for_blocking}</p> <p className="text-neutral-400">{device?.reason_for_blocking}</p>
</div> </div>
)} )}
</div> </div>

View File

@ -1,76 +1,104 @@
'use client' "use client";
import { deviceCartAtom } from '@/lib/atoms' import { deviceCartAtom } from "@/lib/atoms";
import { cn } from '@/lib/utils' import type { Device } from "@/lib/backend-types";
import type { Device } from '@prisma/client' import { cn } from "@/lib/utils";
import { useAtom } from 'jotai' import { useAtom } from "jotai";
import Link from 'next/link' import { Hourglass } from "lucide-react";
import AddDevicesToCartButton from './add-devices-to-cart-button' import Link from "next/link";
import BlockDeviceDialog from './block-device-dialog' import AddDevicesToCartButton from "./add-devices-to-cart-button";
import { Badge } from './ui/badge' import BlockDeviceDialog from "./block-device-dialog";
import { Badge } from "./ui/badge";
export default function DeviceCard({ device, parentalControl }: { device: Device, parentalControl?: boolean }) { export default function DeviceCard({
const [devices, setDeviceCart] = useAtom(deviceCartAtom) device,
parentalControl,
}: { device: Device; parentalControl?: boolean }) {
const [devices, setDeviceCart] = useAtom(deviceCartAtom);
const isChecked = devices.some((d) => d.id === device.id); const isChecked = devices.some((d) => d.id === device.id);
return ( return (
<div <div
onKeyUp={() => { }} onKeyUp={() => {}}
onClick={() => { onClick={() => {
if (parentalControl === true) return if (device.blocked) return;
setDeviceCart((prev) => if (device.is_active === true) return;
devices.some((d) => d.id === device.id) if (device.has_a_pending_payment === true) return;
? prev.filter((d) => d.id !== device.id) if (parentalControl === true) return;
: [...prev, device] setDeviceCart((prev) =>
) devices.some((d) => d.id === device.id)
} ? prev.filter((d) => d.id !== device.id)
} : [...prev, device],
className="w-full"> );
<div className={cn("flex text-sm justify-between items-center my-2 p-4 border rounded-md", isChecked ? "bg-accent" : "bg-")}> }}
<div className=''> className="w-full"
<div className="font-semibold flex flex-col items-start gap-2 mb-2"> >
<Link <div
className="font-medium hover:underline" className={cn(
href={`/devices/${device.id}`} "flex text-sm justify-between items-center my-2 p-4 border rounded-md",
> isChecked ? "bg-accent" : "bg-",
{device.name} device.is_active
</Link> ? "cursor-not-allowed bg-accent-foreground/10 hover:bg-accent-foreground/10"
<Badge variant={"secondary"}> : "cursor-pointer hover:bg-muted",
<span className="font-medium"> )}
{device.mac} >
</span> <div className="">
</Badge> <div className="font-semibold flex flex-col items-start gap-2 mb-2">
</div> <Link
className="font-medium hover:underline"
href={`/devices/${device.id}`}
>
{device.name}
</Link>
<Badge variant={"secondary"}>
<span className="font-medium">{device.mac}</span>
</Badge>
</div>
{device.isActive && ( {device.is_active ? (
<span className="text-muted-foreground"> <div className="text-muted-foreground">
Active until{" "} Active until{" "}
{new Date().toLocaleDateString("en-US", { <span className="font-semibold">
month: "short", {new Date(device.expiry_date || "").toLocaleDateString(
day: "2-digit", "en-US",
year: "numeric", {
})} month: "short",
</span> day: "2-digit",
)} year: "numeric",
},
)}
</span>
</div>
) : (
<p className="text-muted-foreground">Device Inactive</p>
)}
{device.has_a_pending_payment && (
<Link href={`/payments/${device.pending_payment_id}`}>
<span className="flex hover:underline items-center justify-center gap-2 text-muted-foreground text-yellow-600">
Payment Pending <Hourglass size={14} />
</span>
</Link>
)}
{(device.blocked && device.blockedBy === "ADMIN") && ( {device.blocked && device.blocked_by === "ADMIN" && (
<div className="p-2 rounded border my-2 w-full"> <div className="p-2 rounded border my-2 w-full">
<span className='uppercase text-red-500'>Blocked by admin </span> <span className="uppercase text-red-500">Blocked by admin </span>
<p className="text-neutral-500"> <p className="text-neutral-500">{device?.reason_for_blocking}</p>
{device?.reasonForBlocking} </div>
</p> )}
</div> </div>
)} <div>
{!parentalControl ? (
</div> <AddDevicesToCartButton device={device} />
<div> ) : (
{!parentalControl ? ( <BlockDeviceDialog
<AddDevicesToCartButton device={device} /> admin={false}
) : ( type={device.blocked ? "unblock" : "block"}
<BlockDeviceDialog admin={false} type={device.blocked ? "unblock" : "block"} device={device} /> device={device}
)} />
</div> )}
</div> </div>
</div> </div>
) </div>
);
} }

View File

@ -10,7 +10,7 @@ import { tryCatch } from "@/utils/tryCatch";
import { useAtom, useAtomValue, useSetAtom } from "jotai"; import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { CircleDollarSign, Loader2 } from "lucide-react"; import { CircleDollarSign, Loader2 } from "lucide-react";
import { useSession } from "next-auth/react"; import { useSession } from "next-auth/react";
import { usePathname } from "next/navigation"; import { redirect, usePathname } from "next/navigation";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
export default function DevicesForPayment() { export default function DevicesForPayment() {
@ -35,7 +35,7 @@ export default function DevicesForPayment() {
setTotal(baseAmount + (devices.length + 1 - 1) * discountPercentage); setTotal(baseAmount + (devices.length + 1 - 1) * discountPercentage);
}, [months, devices.length]); }, [months, devices.length]);
if (pathname === "/payment") { if (pathname === "/payments") {
return null; return null;
} }
@ -45,6 +45,9 @@ export default function DevicesForPayment() {
device_ids: devices.map((device) => device.id), device_ids: devices.map((device) => device.id),
}; };
if (disabled) {
return "Please wait...";
}
return ( return (
<div className="max-w-lg mx-auto space-y-4 px-4"> <div className="max-w-lg mx-auto space-y-4 px-4">
<div className="flex max-h-[calc(100svh-400px)] flex-col overflow-auto pb-4 gap-4"> <div className="flex max-h-[calc(100svh-400px)] flex-col overflow-auto pb-4 gap-4">
@ -69,15 +72,15 @@ export default function DevicesForPayment() {
<Button <Button
onClick={async () => { onClick={async () => {
setDisabled(true); setDisabled(true);
const [error, respose] = await tryCatch(createPayment(data)); const [error, response] = await tryCatch(createPayment(data));
if (error) { if (error) {
setDisabled(false); setDisabled(false);
toast.error(error.message); toast.error(JSON.stringify(error, null, 2));
return; return;
} }
setDeviceCart([]); setDeviceCart([]);
setMonths(1); setMonths(1);
setDisabled(false); redirect(`/payments/${response.id}`);
}} }}
className="w-full" className="w-full"
disabled={devices.length === 0 || disabled} disabled={devices.length === 0 || disabled}

View File

@ -56,43 +56,6 @@ export async function DevicesTable({
</TableHeader> </TableHeader>
<TableBody className="overflow-scroll"> <TableBody className="overflow-scroll">
{data.map((device) => ( {data.map((device) => (
// <TableRow key={device.id}>
// <TableCell>
// <div className="flex flex-col items-start">
// <Link
// className="font-medium hover:underline"
// href={`/devices/${device.id}`}
// >
// {device.name}
// </Link>
// <span className="text-muted-foreground">
// Active until{" "}
// {new Date().toLocaleDateString("en-US", {
// month: "short",
// day: "2-digit",
// year: "numeric",
// })}
// </span>
// {parentalControl && (
// <div className="p-2 rounded border my-2">
// <span>Comment: </span>
// <p className="text-neutral-500">
// blocked because he was watching youtube
// </p>
// </div>
// )}
// </div>
// </TableCell>
// <TableCell className="font-medium">{device.mac}</TableCell>
// <TableCell>
// {!parentalControl ? (
// <AddDevicesToCartButton device={device} />
// ) : (
// <BlockDeviceButton device={device} />
// )}
// </TableCell>
// </TableRow>
<ClickableRow <ClickableRow
admin={isAdmin} admin={isAdmin}
key={device.id} key={device.id}

View File

@ -15,6 +15,7 @@ import type { Payment } from "@/lib/backend-types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { tryCatch } from "@/utils/tryCatch"; import { tryCatch } from "@/utils/tryCatch";
import { Calendar } from "lucide-react"; import { Calendar } from "lucide-react";
import { redirect } from "next/navigation";
import Pagination from "./pagination"; import Pagination from "./pagination";
import { Badge } from "./ui/badge"; import { Badge } from "./ui/badge";
import { Button } from "./ui/button"; import { Button } from "./ui/button";
@ -86,7 +87,11 @@ export async function PaymentsTable({
const [error, payments] = await tryCatch(getPayments()); const [error, payments] = await tryCatch(getPayments());
if (error) { if (error) {
return <pre>{JSON.stringify(error, null, 2)}</pre>; if (error.message.includes("Unauthorized")) {
redirect("/auth/signin");
} else {
return <pre>{JSON.stringify(error, null, 2)}</pre>;
}
} }
const { data, meta, links } = payments; const { data, meta, links } = payments;
return ( return (

View File

@ -35,6 +35,8 @@ export interface Device {
name: string; name: string;
mac: string; mac: string;
reason_for_blocking: string | null; reason_for_blocking: string | null;
has_a_pending_payment: boolean;
pending_payment_id: string | null;
is_active: boolean; is_active: boolean;
registered: boolean; registered: boolean;
blocked: boolean; blocked: boolean;

View File

@ -2,6 +2,7 @@
import { authOptions } from "@/app/auth"; import { authOptions } from "@/app/auth";
import type { Api400Error, ApiResponse, Device } from "@/lib/backend-types"; import type { Api400Error, ApiResponse, Device } from "@/lib/backend-types";
import { AxiosClient } from "@/utils/axios-client";
import { checkSession } from "@/utils/session"; import { checkSession } from "@/utils/session";
import { getServerSession } from "next-auth"; import { getServerSession } from "next-auth";
import { revalidatePath } from "next/cache"; import { revalidatePath } from "next/cache";
@ -14,7 +15,7 @@ type GetDevicesProps = {
}; };
export async function getDevices({ query }: GetDevicesProps) { export async function getDevices({ query }: GetDevicesProps) {
const session = await checkSession(); const session = await checkSession();
const respose = await fetch( const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/devices/?name=${query}`, `${process.env.SARLINK_API_BASE_URL}/api/devices/?name=${query}`,
{ {
method: "GET", method: "GET",
@ -24,7 +25,10 @@ export async function getDevices({ query }: GetDevicesProps) {
}, },
}, },
); );
const data = (await respose.json()) as ApiResponse<Device>; if (response.status === 401) {
throw new Error("Unauthorized; redirect to /auth/signin");
}
const data = (await response.json()) as ApiResponse<Device>;
return data; return data;
} }

View File

@ -1,6 +1,6 @@
"use server"; "use server";
import { AxiosClient } from "@/utils/AxiosClient"; import { AxiosClient } from "@/utils/axios-client";
export async function getIslands() { export async function getIslands() {
const response = await AxiosClient.get("/islands/"); const response = await AxiosClient.get("/islands/");

View File

@ -1,12 +1,13 @@
import { authOptions } from "@/app/auth";
import axios, { type AxiosError } from "axios"; import axios, { type AxiosError } from "axios";
import type { Session } from "next-auth"; import { type Session, getServerSession } from "next-auth";
import { getSession } from "next-auth/react"; import { getSession } from "next-auth/react";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfHeaderName = "X-CSRFToken";
const ApiClient = () => { const APIClient = () => {
const instance = axios.create({ const instance = axios.create({
baseURL: process.env.SARLINK_API_BASE_URL, baseURL: process.env.SARLINK_API_BASE_URL,
headers: { headers: {
@ -15,11 +16,13 @@ const ApiClient = () => {
}); });
let lastSession: Session | null = null; let lastSession: Session | null = null;
console.log("Last session: ", lastSession);
instance.interceptors.request.use( instance.interceptors.request.use(
async (request) => { async (request) => {
if (lastSession == null || Date.now() > Date.parse(lastSession.expires)) { if (lastSession == null || Date.now() > Date.parse(lastSession.expires)) {
const session = await getSession(); const session = await getServerSession(authOptions);
console.log("Server session: ", session);
lastSession = session; lastSession = session;
} }
@ -27,23 +30,24 @@ const ApiClient = () => {
request.headers.Authorization = `Token ${lastSession.apiToken}`; request.headers.Authorization = `Token ${lastSession.apiToken}`;
} else { } else {
request.headers.Authorization = undefined; request.headers.Authorization = undefined;
return redirect("/auth/signin");
} }
return request; return request;
}, },
(error) => { (error) => {
console.error("API Error: ", error); console.error("API Request Error: ", error);
throw error; throw error;
}, },
); );
instance.interceptors.response.use( instance.interceptors.response.use(
async (response) => { async (response) => {
return response; return response;
}, },
async (error: AxiosError) => { async (error: AxiosError) => {
if (error?.response?.status === 401) { if (error?.response?.status === 401) {
return redirect("/auth/signin"); // Redirect to the signin page if the user is unauthorized
redirect("/auth/signin");
} }
return Promise.reject(error); return Promise.reject(error);
}, },
@ -52,4 +56,4 @@ const ApiClient = () => {
return instance; return instance;
}; };
export const AxiosClient = ApiClient(); export const AxiosClient = APIClient();