Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add option to edit link
Marc Seitzef5276522008
diff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsxindex 1d657188..1b91cdd0 100644--- a/components/links/link-sheet/index.tsx+++ b/components/links/link-sheet/index.tsx@@ -16,7 +16,8 @@ import { useRouter } from "next/router";import { useDocumentLinks } from "@/lib/swr/use-document";import { mutate } from "swr";-const DEFAULT_LINK_PROPS = {+export const DEFAULT_LINK_PROPS = {+ id: null,name: null,expiresAt: null,password: null,@@ -24,6 +25,7 @@ const DEFAULT_LINK_PROPS = {};export type DEFAULT_LINK_TYPE = {+ id: string | null;name: string | null;expiresAt: Date | null;password: string | null;@@ -47,8 +49,18 @@ export default function LinkSheet({ isOpen, setIsOpen, currentLink }: { isOpen:event.preventDefault();setIsLoading(true);- const response = await fetch("/api/links", {- method: "POST",++ let endpoint = "/api/links";+ let method = "POST";++ if (currentLink) {+ // Assuming that your endpoint to update links appends the link's ID to the URL+ endpoint = `/api/links/${currentLink.id}`;+ method = "PUT";+ }++ const response = await fetch(endpoint, {+ method: method,headers: {"Content-Type": "application/json",},@@ -62,17 +74,26 @@ export default function LinkSheet({ isOpen, setIsOpen, currentLink }: { isOpen:throw new Error(`HTTP error! status: ${response.status}`);}- const newLink = await response.json();-- // Update local data with the new link- mutate(- `/api/documents/${encodeURIComponent(documentId)}/links`,- [...(links || []), newLink],- false- );+ const returnedLink = await response.json();++ if (currentLink) {+ // Update the link in the list of links+ mutate(+ `/api/documents/${encodeURIComponent(documentId)}/links`,+ (links || []).map(link => link.id === currentLink.id ? returnedLink : link),+ false+ );+ } else {+ // Add the new link to the list of links+ mutate(+ `/api/documents/${encodeURIComponent(documentId)}/links`,+ [...(links || []), returnedLink],+ false+ );+ }+ setData(DEFAULT_LINK_PROPS);setIsLoading(false);-}diff --git a/components/links/links-table.tsx b/components/links/links-table.tsxindex 1f273546..80e1172d 100644--- a/components/links/links-table.tsx+++ b/components/links/links-table.tsx@@ -29,14 +29,32 @@ import MoreHorizontal from "../shared/icons/more-horizontal";import { Skeleton } from "../ui/skeleton";import LinksVisitors from "./links-visitors";import ChevronDown from "../shared/icons/chevron-down";+import LinkSheet, { DEFAULT_LINK_PROPS, type DEFAULT_LINK_TYPE } from "./link-sheet";+import { useState } from "react";+import { LinkWithViews } from "@/lib/types";+export default function LinksTable() {const { links } = useDocumentLinks();+ const [isLinkSheetVisible, setIsLinkSheetVisible] = useState<boolean>(false);+ const [selectedLink, setSelectedLink] = useState<DEFAULT_LINK_TYPE>(DEFAULT_LINK_PROPS);+const handleCopyToClipboard = (id: string) => {copyToClipboard(`${process.env.NEXT_PUBLIC_BASE_URL}/view/${id}`, "Link copied to clipboard.");};++ const handleEditLink = (link: LinkWithViews) => {+ setSelectedLink({+ id: link.id,+ name: link.name,+ expiresAt: link.expiresAt,+ password: link.password,+ emailProtected: link.emailProtected || true,+ });+ setIsLinkSheetVisible(true);+ };return (<div className="w-full sm:p-4">@@ -118,7 +136,11 @@ export default function LinksTable() {</DropdownMenuTrigger><DropdownMenuContent align="end"><DropdownMenuLabel>Actions</DropdownMenuLabel>- <DropdownMenuItem>Edit Link</DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => handleEditLink(link)}+ >+ Edit Link+ </DropdownMenuItem><DropdownMenuItem>Make copy</DropdownMenuItem><DropdownMenuSeparator /><DropdownMenuItem className="text-red-500 focus:text-red-200 focus:bg-red-900">@@ -156,6 +178,11 @@ export default function LinksTable() {</TableBody></Table></div>+ <LinkSheet+ isOpen={isLinkSheetVisible}+ setIsOpen={setIsLinkSheetVisible}+ currentLink={selectedLink}+ /></div>);}\ No newline at end of filediff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.tsindex 43cc24a9..78f519a2 100644--- a/pages/api/links/[id]/index.ts+++ b/pages/api/links/[id]/index.ts@@ -1,5 +1,8 @@import { NextApiRequest, NextApiResponse } from "next";import prisma from "@/lib/prisma";+import { getServerSession } from "next-auth/next";+import { hashPassword } from "@/lib/utils";+import { authOptions } from "../../auth/[...nextauth]";export default async function handle(req: NextApiRequest,@@ -27,9 +30,52 @@ export default async function handle(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`);+ }++ if (req.method === "PUT") {+ // PUT /api/links/:id+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { id } = req.query as { id: string };+ const { documentId, password, expiresAt, ...linkData } = req.body;++ const hashedPassword =+ password && password.length > 0 ? await hashPassword(password) : null;+ const exat = expiresAt ? new Date(expiresAt) : null;++ // Update the link in the database+ const updatedLink = await prisma.link.update({+ where: { id: id },+ data: {+ documentId: documentId,+ password: hashedPassword,+ name: linkData.name || null,+ emailProtected: linkData.emailProtected || false,+ expiresAt: exat,+ },+ include: {+ views: {+ orderBy: {+ viewedAt: "desc",+ }+ },+ _count: {+ select: { views: true },+ },+ },+ });++ if (!updatedLink) {+ return res.status(404).json({ error: "Link not found" });+ }++ return res.status(200).json(updatedLink);}++ // We only allow GET and PUT requests+ res.setHeader("Allow", ["GET", "PUT"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);}