Skip to content

Commit

Permalink
feat: add duplicate link
Browse files Browse the repository at this point in the history
  • Loading branch information
mfts committed Jun 12, 2024
1 parent 898c8f7 commit 815f345
Show file tree
Hide file tree
Showing 2 changed files with 132 additions and 1 deletion.
43 changes: 42 additions & 1 deletion components/links/links-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,39 @@ export default function LinksTable({
}, 0);
};

const handleDuplicateLink = async (link: LinkWithViews) => {
setIsLoading(true);

const response = await fetch(
`/api/links/${link.id}/duplicate?teamId=${teamInfo?.currentTeam?.id}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
},
);

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const duplicatedLink = await response.json();
const endpointTargetType = `${targetType.toLowerCase()}s`; // "documents" or "datarooms"

// Update the duplicated link in the list of links
mutate(
`/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${encodeURIComponent(
link.documentId ?? link.dataroomId ?? "",
)}/links`,
(links || []).concat(duplicatedLink),
false,
);

toast.success("Link duplicated successfully");
setIsLoading(false);
};

const handleArchiveLink = async (
linkId: string,
targetId: string,
Expand Down Expand Up @@ -290,7 +323,10 @@ export default function LinksTable({
<TableCell className="text-center sm:text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<Button
variant="ghost"
className="h-8 w-8 p-0 group-hover/row:ring-1 group-hover/row:ring-gray-200 group-hover/row:dark:ring-gray-700"
>
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
Expand All @@ -303,6 +339,11 @@ export default function LinksTable({
>
Edit Link
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleDuplicateLink(link)}
>
Duplicate Link
</DropdownMenuItem>
<DropdownMenuItem
className="text-destructive focus:bg-destructive focus:text-destructive-foreground"
onClick={() =>
Expand Down
90 changes: 90 additions & 0 deletions pages/api/links/[id]/duplicate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { NextApiRequest, NextApiResponse } from "next";

import { getServerSession } from "next-auth/next";

import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";

import { authOptions } from "../../auth/[...nextauth]";

export default async function handle(
req: NextApiRequest,
res: NextApiResponse,
) {
if (req.method === "POST") {
// PUT /api/links/:id/duplicate
const session = await getServerSession(req, res, authOptions);
if (!session) {
return res.status(401).end("Unauthorized");
}

const { id, teamId } = req.query as { id: string; teamId: string };

try {
const team = await prisma.team.findUnique({
where: {
id: teamId,
users: {
some: {
userId: (session.user as CustomUser).id,
},
},
},
select: { id: true },
});

if (!team) {
return res.status(401).end("Unauthorized");
}

const link = await prisma.link.findUnique({
where: { id },
include: {
dataroom: {
select: {
teamId: true,
},
},
document: {
select: { teamId: true },
},
},
});

if (!link) {
return res.status(404).json({ error: "Link not found" });
}

const { dataroom, document, ...linkData } = link;

const newLinkName = linkData.name
? linkData.name + " (Copy)"
: `Link #${linkData.id.slice(-5)} (Copy)`;
const newLink = await prisma.link.create({
data: {
...linkData,
id: undefined,
slug: linkData.slug ? linkData.slug + "-copy" : null,
name: newLinkName,
createdAt: undefined,
updatedAt: undefined,
},
});

const linkWithView = {
...newLink,
_count: { views: 0 },
views: [],
};

return res.status(201).json(linkWithView);
} catch (error) {
errorhandler(error, res);
}
}

// We only allow PUT requests
res.setHeader("Allow", ["POST"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}

0 comments on commit 815f345

Please sign in to comment.