Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

update document stats card with swr loading

Marc Seitz61b094d7e4f7
diff --git a/components/documents/stats-card.tsx b/components/documents/stats-card.tsx
index 55936222..a4940062 100644
--- a/components/documents/stats-card.tsx
+++ b/components/documents/stats-card.tsx
@@ -1,11 +1,24 @@
-import { classNames } from "@/lib/utils";
+import { useStats } from "@/lib/swr/use-stats";
+import ErrorPage from "next/error";
+import StatsElement from "./stats-element";
+import StatsElementPlaceholder from "./stats-element-placeholder";
export default function StatsCard() {
- const stats = [
- { name: "Number of views", value: 0, active: true },
+ const { stats, error } = useStats();
+
+ if (error && error.status === 404) {
+ return <ErrorPage statusCode={404} />;
+ }
+
+ const statistics = [
+ {
+ name: "Number of views",
+ value: stats?.views.length.toString() ?? "0",
+ active: true,
+ },
{
name: "Number of unique viewers",
- value: 0,
+ value: stats?.groupedViews.length.toString() ?? "0",
active: true,
},
{
@@ -19,48 +32,13 @@ export default function StatsCard() {
return (
<div className="grid grid-cols-1 bg-gray-700/10 sm:grid-cols-2 lg:grid-cols-4">
- {stats.map((stat, statIdx) => (
- <div
- key={stat.name}
- className={classNames(
- statIdx % 2 === 1
- ? "sm:border-l"
- : statIdx === 2
- ? "lg:border-l"
- : "",
- "border-t border-white/5 py-6 px-4 sm:px-6 lg:px-8"
- )}
- >
- <p
- className={classNames(
- !stat.active ? "text-gray-700" : "text-gray-400",
- "text-sm font-medium leading-6"
- )}
- >
- {stat.name}
- </p>
- <p className="mt-2 flex items-baseline gap-x-2">
- <span
- className={classNames(
- !stat.active ? "text-gray-700" : "text-white",
- "text-4xl font-semibold tracking-tight "
- )}
- >
- {stat.value}
- </span>
- {stat.unit ? (
- <span
- className={classNames(
- !stat.active ? "text-gray-700" : "text-gray-400",
- "text-sm"
- )}
- >
- {stat.unit}
- </span>
- ) : null}
- </p>
- </div>
- ))}
+ {stats
+ ? statistics.map((stat, statIdx) => (
+ <StatsElement stat={stat} statIdx={statIdx} />
+ ))
+ : Array.from({ length: 4 }).map((_, i) => (
+ <StatsElementPlaceholder key={i} />
+ ))}
</div>
);
}
diff --git a/components/documents/stats-element-placeholder.tsx b/components/documents/stats-element-placeholder.tsx
new file mode 100644
index 00000000..6d012855
--- /dev/null
+++ b/components/documents/stats-element-placeholder.tsx
@@ -0,0 +1,17 @@
+import { classNames } from "@/lib/utils";
+
+export default function StatsElementPlaceholder({ key }: { key: number }) {
+ return (
+ <div
+ className={classNames(
+ key % 2 === 1 ? "sm:border-l" : key === 2 ? "lg:border-l" : "",
+ "border-t border-white/5 py-6 px-4 sm:px-6 lg:px-8"
+ )}
+ >
+ <div className="h-4 w-full animate-pulse rounded-md bg-gray-800" />
+ <div className="mt-4 flex gap-x-2">
+ <div className="h-8 w-8 animate-pulse rounded-md bg-gray-800" />
+ </div>
+ </div>
+ );
+}
diff --git a/components/documents/stats-element.tsx b/components/documents/stats-element.tsx
new file mode 100644
index 00000000..dba3eb7e
--- /dev/null
+++ b/components/documents/stats-element.tsx
@@ -0,0 +1,53 @@
+import { classNames } from "@/lib/utils";
+
+interface Stat {
+ name: string;
+ value: string;
+ unit?: string;
+ active: boolean;
+}
+interface StatsElementProps {
+ stat: Stat;
+ statIdx: number;
+}
+
+export default function StatsElement({ stat, statIdx }: StatsElementProps) {
+ return (
+ <div
+ key={stat.name}
+ className={classNames(
+ statIdx % 2 === 1 ? "sm:border-l" : statIdx === 2 ? "lg:border-l" : "",
+ "border-t border-white/5 py-6 px-4 sm:px-6 lg:px-8"
+ )}
+ >
+ <p
+ className={classNames(
+ !stat.active ? "text-gray-700" : "text-gray-400",
+ "text-sm font-medium leading-6"
+ )}
+ >
+ {stat.name}
+ </p>
+ <p className="mt-2 flex items-baseline gap-x-2">
+ <span
+ className={classNames(
+ !stat.active ? "text-gray-700" : "text-white",
+ "text-4xl font-semibold tracking-tight "
+ )}
+ >
+ {stat.value}
+ </span>
+ {stat.unit ? (
+ <span
+ className={classNames(
+ !stat.active ? "text-gray-700" : "text-gray-400",
+ "text-sm"
+ )}
+ >
+ {stat.unit}
+ </span>
+ ) : null}
+ </p>
+ </div>
+ );
+}
diff --git a/lib/swr/use-stats.ts b/lib/swr/use-stats.ts
new file mode 100644
index 00000000..ba8c0ffd
--- /dev/null
+++ b/lib/swr/use-stats.ts
@@ -0,0 +1,37 @@
+import { useRouter } from "next/router";
+import useSWR from "swr";
+import { fetcher } from "@/lib/utils";
+import { LinkWithViews } from "@/lib/types";
+import { Document, View } from "@prisma/client";
+
+interface GroupedView {
+ viewerEmail: string;
+ _count: { id: number };
+}
+
+interface StatsData {
+ views: View[];
+ groupedViews: GroupedView[];
+}
+
+export function useStats() {
+ const router = useRouter();
+
+ const { id } = router.query as {
+ id: string;
+ };
+
+ const { data: stats, error } = useSWR<StatsData>(
+ id && `/api/documents/${encodeURIComponent(id)}/stats`,
+ fetcher,
+ {
+ dedupingInterval: 10000,
+ }
+ );
+
+ return {
+ stats,
+ loading: !error && !stats,
+ error,
+ };
+}
diff --git a/pages/api/documents/[id]/stats.ts b/pages/api/documents/[id]/stats.ts
new file mode 100644
index 00000000..23bc0efa
--- /dev/null
+++ b/pages/api/documents/[id]/stats.ts
@@ -0,0 +1,46 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { getServerSession } from "next-auth/next";
+import prisma from "@/lib/prisma";
+import { authOptions } from "../../auth/[...nextauth]";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ if (req.method === "GET") {
+ // GET /api/documents/:id
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end({ error: "Unauthorized" });
+ }
+
+ const { id } = req.query as { id: string };
+
+ try {
+ const views = await prisma.view.findMany({
+ where: { documentId: id },
+ });
+
+ const groupedViews = await prisma.view.groupBy({
+ by: ["viewerEmail"],
+ where: { documentId: id },
+ _count: { id: true },
+ });
+
+ const stats = { views, groupedViews };
+
+ // TODO: Check that the user is owner of the document, otherwise return 401
+
+ res.status(200).json(stats);
+ } catch (error) {
+ return res.status(500).end({
+ message: "Internal Server Error",
+ error: (error as Error).message,
+ });
+ }
+ } else {
+ // We only allow GET and POST requests
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}