Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add swr for better document loading
Marc Seitzf2376ba6d191
diff --git a/components/documents/document-card.tsx b/components/documents/document-card.tsxnew file mode 100644index 00000000..6268fbbe--- /dev/null+++ b/components/documents/document-card.tsx@@ -0,0 +1,59 @@+import { getExtension } from "@/lib/utils";+import { ChevronRightIcon } from "@heroicons/react/20/solid";+import { DocumentDuplicateIcon } from "@heroicons/react/24/outline";+import Link from "next/link";+import { DocumentWithLinksAndLinkCount } from "@/lib/types";+import Notification from "@/components/Notification";++export default function DocumentsCard({+ document,+}: {+ document: DocumentWithLinksAndLinkCount;+}) {+ function handleCopyToClipboard(id: string) {+ navigator.clipboard.writeText(+ `${process.env.NEXT_PUBLIC_BASE_URL}/view/${id}`+ );++ }++ return (+ <li className="relative flex justify-between items-center space-x-4 px-4 py-4 sm:px-6 lg:px-8">+ <div className="min-w-0 flex">+ <div className="flex-col">+ <div className="flex items-center">+ <h2 className="min-w-0 text-sm font-semibold leading-6 text-white">+ <Link href={`/documents/${document.id}`} className="flex gap-x-2">+ <span className="truncate">{document.name}</span>+ <span className="text-gray-400">/</span>+ <span className="whitespace-nowrap text-gray-500">+ {getExtension(document.file)}+ </span>+ <span className="absolute inset-0" />+ </Link>+ </h2>+ <div className="flex ml-2">+ <button+ className="text-gray-500 hover:text-gray-700 z-10"+ onClick={() => handleCopyToClipboard(document.links[0].id)}+ title="Copy to clipboard"+ >+ <DocumentDuplicateIcon className="h-5 w-5" aria-hidden="true" />+ </button>+ </div>+ </div>+ <div className="mt-3 flex items-center gap-x-2.5 text-xs leading-5 text-gray-400">+ <p className="truncate">{`${document._count.links} ${+ document._count.links === 1 ? "Link" : "Links"+ }`}</p>+ </div>+ </div>+ </div>++ <ChevronRightIcon+ className="h-5 w-5 flex-none text-gray-400"+ aria-hidden="true"+ />+ </li>+ );+}diff --git a/lib/swr/use-documents.ts b/lib/swr/use-documents.tsnew file mode 100644index 00000000..3730bd68--- /dev/null+++ b/lib/swr/use-documents.ts@@ -0,0 +1,21 @@+import { useRouter } from "next/router";+import useSWR from "swr";+import { fetcher } from "@/lib/utils";+import { DocumentWithLinksAndLinkCount } from "@/lib/types";++export default function useDocuments() {+ const router = useRouter();++ const { data: documents, isValidating } = useSWR<+ DocumentWithLinksAndLinkCount[]+ >(router.isReady && `/api/documents`, fetcher, {+ revalidateOnFocus: false,+ dedupingInterval: 30000,+ });++ return {+ documents,+ loading: documents ? false : true,+ isValidating,+ };+}diff --git a/lib/types.ts b/lib/types.tsindex 6599f495..5948fcdc 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -1,5 +1,13 @@import { User as NextAuthUser } from "next-auth";+import { Document, Link } from "@prisma/client";export interface CustomUser extends NextAuthUser {id: string;}++export interface DocumentWithLinksAndLinkCount extends Document {+ _count: {+ links: number;+ };+ links: Link[];+}diff --git a/lib/utils.ts b/lib/utils.tsindex 5f5e08c0..c087ce28 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -7,3 +7,23 @@ export function getExtension(url: string) {// @ts-ignorereturn url.split(/[#?]/)[0].split(".").pop().trim();}++interface SWRError extends Error {+ status: number;+}++export async function fetcher<JSON = any>(+ input: RequestInfo,+ init?: RequestInit+): Promise<JSON> {+ const res = await fetch(input, init);++ if (!res.ok) {+ const error = await res.text();+ const err = new Error(error) as SWRError;+ err.status = res.status;+ throw err;+ }++ return res.json();+}diff --git a/package-lock.json b/package-lock.jsonindex bafc55d3..f61a8653 100644--- a/package-lock.json+++ b/package-lock.json@@ -29,6 +29,7 @@"react-dom": "18.2.0","react-hot-toast": "^2.4.1","react-pdf": "^7.0.1",+ "swr": "^2.1.5","tailwindcss": "3.3.2","typescript": "5.0.4"},@@ -4697,6 +4698,17 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/swr": {+ "version": "2.1.5",+ "resolved": "https://registry.npmjs.org/swr/-/swr-2.1.5.tgz",+ "integrity": "sha512-/OhfZMcEpuz77KavXST5q6XE9nrOBOVcBLWjMT+oAE/kQHyE3PASrevXCtQDZ8aamntOfFkbVJp7Il9tNBQWrw==",+ "dependencies": {+ "use-sync-external-store": "^1.2.0"+ },+ "peerDependencies": {+ "react": "^16.11.0 || ^17.0.0 || ^18.0.0"+ }+ },"node_modules/synckit": {"version": "0.8.5","resolved": "https://registry.npmjs.org/synckit/-/synckit-0.8.5.tgz",@@ -5001,6 +5013,14 @@"punycode": "^2.1.0"}},+ "node_modules/use-sync-external-store": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",+ "integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==",+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"+ }+ },"node_modules/util-deprecate": {"version": "1.0.2","resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",@@ -8284,6 +8304,14 @@"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz","integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="},+ "swr": {+ "version": "2.1.5",+ "resolved": "https://registry.npmjs.org/swr/-/swr-2.1.5.tgz",+ "integrity": "sha512-/OhfZMcEpuz77KavXST5q6XE9nrOBOVcBLWjMT+oAE/kQHyE3PASrevXCtQDZ8aamntOfFkbVJp7Il9tNBQWrw==",+ "requires": {+ "use-sync-external-store": "^1.2.0"+ }+ },"synckit": {"version": "0.8.5","resolved": "https://registry.npmjs.org/synckit/-/synckit-0.8.5.tgz",@@ -8504,6 +8532,12 @@"punycode": "^2.1.0"}},+ "use-sync-external-store": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",+ "integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==",+ "requires": {}+ },"util-deprecate": {"version": "1.0.2","resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",diff --git a/package.json b/package.jsonindex d434c1c7..f2318709 100644--- a/package.json+++ b/package.json@@ -33,6 +33,7 @@"react-dom": "18.2.0","react-hot-toast": "^2.4.1","react-pdf": "^7.0.1",+ "swr": "^2.1.5","tailwindcss": "3.3.2","typescript": "5.0.4"},@@ -40,4 +41,4 @@"@tailwindcss/forms": "^0.5.3","prisma": "^4.14.1"}-}\ No newline at end of file+}diff --git a/pages/api/documents.ts b/pages/api/documents.tsindex 79cdb237..513e446d 100644--- a/pages/api/documents.ts+++ b/pages/api/documents.ts@@ -9,50 +9,84 @@ export default async function handle(req: NextApiRequest,res: NextApiResponse) {- // We only allow POST requests- if (req.method !== "POST") {- res.status(405).json({ message: "Method Not Allowed" });- return;- }+ if (req.method === "GET") {+ // GET /api/documents+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end({ error: "Unauthorized" });+ }- const session = await getServerSession(req, res, authOptions);- if (!session) {- res.status(401).json({ error: "Unauthorized" });- return;- }+ try {+ const documents = await prisma.document.findMany({+ where: {+ ownerId: (session.user as CustomUser).id,+ },+ orderBy: {+ createdAt: "desc",+ },+ include: {+ _count: {+ select: { links: true },+ },+ links: {+ take: 1,+ select: { id: true },+ },+ },+ });++ res.status(200).json(documents);+ } catch (error) {+ return res.status(500).end({+ message: "Internal Server Error",+ error: (error as Error).message,+ });+ }+ } else if (req.method === "POST") {+ // POST /api/documents+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).json({ error: "Unauthorized" });+ return;+ }++ // Assuming data is an object with `name` and `description` properties+ const { name, url, description } = req.body;++ // Get the file extension and save it as the type+ const type = getExtension(name);++ // You could perform some validation here++ try {+ // Save data to the database+ const document = await prisma.document.create({+ data: {+ name: name,+ description: description,+ file: url,+ type: type,+ ownerId: (session.user as CustomUser).id,+ },+ });++ const link = await prisma.link.create({+ data: {+ documentId: document.id,+ // url: nanoid(),+ },+ });- // Assuming data is an object with `name` and `description` properties- const { name, url, description } = req.body;-- // Get the file extension and save it as the type- const type = getExtension(name);-- // You could perform some validation here-- try {- // Save data to the database- const document = await prisma.document.create({- data: {- name: name,- description: description,- file: url,- type: type,- ownerId: (session.user as CustomUser).id,- },- });-- const link = await prisma.link.create({- data: {- documentId: document.id,- // url: nanoid(),- },- });-- res.status(201).json({ document, linkId: link.id });- } catch (error) {- res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });+ res.status(201).json({ document, linkId: link.id });+ } catch (error) {+ res.status(500).json({+ message: "Internal Server Error",+ error: (error as Error).message,+ });+ }+ } else {+ // We only allow GET and POST requests+ res.setHeader("Allow", ["GET", "POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);}}diff --git a/pages/documents.tsx b/pages/documents.tsxindex 6bccb084..21b58268 100644--- a/pages/documents.tsx+++ b/pages/documents.tsx@@ -1,96 +1,9 @@-import { GetServerSideProps } from "next";-import prisma from "@/lib/prisma";-import { ChevronRightIcon } from "@heroicons/react/20/solid";import Sidebar from "@/components/Sidebar";-import { getServerSession } from "next-auth/next";-import { CustomUser } from "@/lib/types";-import { authOptions } from "@/pages/api/auth/[...nextauth]";-import { Document, Link as DocumentLink } from "@prisma/client";-import Link from "next/link";-import { getExtension } from "@/lib/utils";-import { DocumentDuplicateIcon } from "@heroicons/react/24/outline";-import toast from "react-hot-toast";-import Notification from "@/components/Notification";+import useDocuments from "@/lib/swr/use-documents";+import DocumentCard from "@/components/documents/document-card";-export const getServerSideProps: GetServerSideProps = async (context) => {- const session = await getServerSession(context.req, context.res, authOptions);- const userId = (session?.user as CustomUser)?.id;-- if (!userId) {- return {- redirect: {- destination: "/",- permanent: false,- },- };- }-- const page = context.query.page ? parseInt(context.query.page as string) : 1;- const pageSize = 10; // Change this to adjust the number of documents per page-- const skip = (page - 1) * pageSize;-- const documents = await prisma.document.findMany({- where: {- ownerId: userId,- },- orderBy: {- createdAt: "desc",- },- include: {- _count: {- select: { links: true },- },- links: true,- },- skip: skip,- take: pageSize,- });-- const totalDocuments = await prisma.document.count({- where: {- ownerId: userId,- },- });-- const totalPages = Math.ceil(totalDocuments / pageSize);-- const serializedDocuments = documents.map((document) => ({- ...document,- createdAt: document.createdAt.toISOString(),- }));-- return {- props: { documents: serializedDocuments, currentPage: page, totalPages },- };-};--// Define a type for the props expected by your Documents component-interface DocumentsWithCount extends Document {- _count: {- links: number;- };- links: DocumentLink[];-}--interface DocumentsProps {- documents: DocumentsWithCount[];-}--export default function Documents({- documents,- currentPage,- totalPages,-}: DocumentsProps & { currentPage: number; totalPages: number }) {- const handleCopyToClipboard = (id: string) => {- navigator.clipboard.writeText(- `${process.env.NEXT_PUBLIC_BASE_URL}/view/${id}`- );-- toast.custom((t) => (- <Notification t={t} closeToast={() => toast.dismiss(t.id)} message={``} />- ));- };+export default function Documents() {+ const { documents } = useDocuments();return (<>@@ -103,80 +16,18 @@ export default function Documents({</h1></header>- {/* Document list */}+ {/* Documents list */}<ul role="list" className="divide-y divide-white/5">- {documents.map((document) => {- return (- <li- key={document.id}- className="relative flex justify-between items-center space-x-4 px-4 py-4 sm:px-6 lg:px-8"- >- <div className="min-w-0 flex">- <div className="flex-col">- <div className="flex items-center">- <h2 className="min-w-0 text-sm font-semibold leading-6 text-white">- <Link- href={`/documents/${document.id}`}- className="flex gap-x-2"- >- <span className="truncate">{document.name}</span>- <span className="text-gray-400">/</span>- <span className="whitespace-nowrap text-gray-500">- {getExtension(document.file)}- </span>- <span className="absolute inset-0" />- </Link>- </h2>- <div className="flex ml-2">- <button- className="text-gray-500 hover:text-gray-700 z-10"- onClick={() =>- handleCopyToClipboard(document.links[0].id)- }- title="Copy to clipboard"- >- <DocumentDuplicateIcon- className="h-5 w-5"- aria-hidden="true"- />- </button>- </div>- </div>- <div className="mt-3 flex items-center gap-x-2.5 text-xs leading-5 text-gray-400">- <p className="truncate">{`${document._count.links} ${- document._count.links === 1 ? "Link" : "Links"- }`}</p>- </div>- </div>- </div>-- <ChevronRightIcon- className="h-5 w-5 flex-none text-gray-400"- aria-hidden="true"- />- </li>- );- })}+ {documents ? (+ documents.map((document) => {+ return <DocumentCard key={document.id} document={document} />;+ })+ ) : (+ <div className="flex justify-center items-center h-96">+ <p className="text-gray-400">Loading documents</p>+ </div>+ )}</ul>- {/* Pagination */}- {totalPages > 1 && (- <div className="flex justify-between mx-10">- <Link- href={currentPage > 1 ? `?page=${currentPage - 1}` : "#"}- passHref- >- <button disabled={currentPage === 1}>Previous</button>- </Link>- <Link- href={- currentPage < totalPages ? `?page=${currentPage + 1}` : "#"- }- passHref- >- <button disabled={currentPage === totalPages}>Next</button>- </Link>- </div>- )}</main></Sidebar></div>