sarlink-portal/queries/devices.ts
i701 7e49bf119a
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 6m28s
refactor: update axios client import, enhance device and payment handling, and add cancel payment button component
2025-04-08 21:37:51 +05:00

83 lines
2.1 KiB
TypeScript

"use server";
import { authOptions } from "@/app/auth";
import type { Api400Error, ApiResponse, Device } from "@/lib/backend-types";
import { AxiosClient } from "@/utils/axios-client";
import { checkSession } from "@/utils/session";
import { getServerSession } from "next-auth";
import { revalidatePath } from "next/cache";
type GetDevicesProps = {
query?: string;
page?: number;
sortBy?: string;
status?: string;
};
export async function getDevices({ query }: GetDevicesProps) {
const session = await checkSession();
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/devices/?name=${query}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
},
);
if (response.status === 401) {
throw new Error("Unauthorized; redirect to /auth/signin");
}
const data = (await response.json()) as ApiResponse<Device>;
return data;
}
export async function getDevice({ deviceId }: { deviceId: string }) {
const session = await checkSession();
const respose = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/devices/${deviceId}/`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
},
);
const device = (await respose.json()) as Device;
return device;
}
export async function addDevice({
name,
mac,
}: {
name: string;
mac: string;
}) {
type SingleDevice = Pick<Device, "name" | "mac">;
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/devices/`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
body: JSON.stringify({
name: name,
mac: mac,
}),
},
);
if (!response.ok) {
const errorData = await response.json();
// Throw an error with the message from the API
throw new Error(errorData.message || "Something went wrong.");
}
const data = (await response.json()) as SingleDevice;
revalidatePath("/devices");
return data;
}