refactor: enhance error handling and add pagination to device queries
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 1m37s

This commit is contained in:
2025-04-12 14:35:23 +05:00
parent d60dd3af14
commit aff9d26e0e
8 changed files with 134 additions and 63 deletions

View File

@ -12,7 +12,9 @@ import {
import { getDevices } from "@/queries/devices";
import { tryCatch } from "@/utils/tryCatch";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import ClickableRow from "./clickable-row";
import ClientErrorMessage from "./client-error-message";
import DeviceCard from "./device-card";
import Pagination from "./pagination";
@ -30,15 +32,22 @@ export async function DevicesTable({
const session = await getServerSession(authOptions);
const isAdmin = session?.user?.is_superuser;
const query = (await searchParams)?.query || "";
const page = (await searchParams)?.page || 1;
const [error, devices] = await tryCatch(getDevices({ query: query }));
const limit = 10; // Items per page
const offset = (page - 1) * limit; // Calculate offset based on page
const [error, devices] = await tryCatch(
getDevices({ query: query, limit: limit, offset: offset }),
);
if (error) {
return <pre>{JSON.stringify(error, null, 2)}</pre>;
if (error.message === "Invalid token.") redirect("/auth/signin");
return <ClientErrorMessage message={error.message} />;
}
const { meta, data } = devices;
const { meta, data, links } = devices;
return (
<div>
{data.length === 0 ? (
{data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
<h3>No devices yet.</h3>
</div>
@ -55,7 +64,7 @@ export async function DevicesTable({
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{data.map((device) => (
{data?.map((device) => (
<ClickableRow
admin={isAdmin}
key={device.id}
@ -67,27 +76,26 @@ export async function DevicesTable({
<TableFooter>
<TableRow>
<TableCell colSpan={2}>
{query.length > 0 && (
{query?.length > 0 && (
<p className="text-sm text-muted-foreground">
Showing {meta.total} locations for &quot;{query}
Showing {meta?.total} locations for &quot;{query}
&quot;
</p>
)}
</TableCell>
<TableCell className="text-muted-foreground">
{meta.total} devices
{meta?.total} devices
</TableCell>
</TableRow>
</TableFooter>
</Table>
<Pagination
totalPages={meta.total / meta.per_page}
currentPage={meta.current_page}
totalPages={meta?.last_page}
currentPage={meta?.current_page}
/>
<pre>{JSON.stringify(meta, null, 2)}</pre>
</div>
<div className="sm:hidden my-4">
{data.map((device) => (
{data?.map((device) => (
<DeviceCard
parentalControl={parentalControl}
key={device.id}