added new api route + fixed dropdown

This commit is contained in:
daniel31x13 2023-10-29 00:57:24 -04:00
parent 2856e23a4a
commit 16024f40be
12 changed files with 348 additions and 203 deletions

View File

@ -96,7 +96,6 @@ Here are the other ways to support/cheer this project:
- Starring this repository. - Starring this repository.
- Joining us on [Discord](https://discord.com/invite/CtuYV47nuJ). - Joining us on [Discord](https://discord.com/invite/CtuYV47nuJ).
- Following @daniel31x13 on [Mastodon](https://mastodon.social/@daniel31x13), [Twitter](https://twitter.com/daniel31x13) and [GitHub](https://github.com/daniel31x13).
- Referring Linkwarden to a friend. - Referring Linkwarden to a friend.
If you did any of the above, Thanksss! Otherwise thanks. If you did any of the above, Thanksss! Otherwise thanks.

View File

@ -15,6 +15,13 @@ type Props = {
className?: string; className?: string;
}; };
type DropdownTrigger =
| {
x: number;
y: number;
}
| false;
export default function CollectionCard({ collection, className }: Props) { export default function CollectionCard({ collection, className }: Props) {
const { setModal } = useModalStore(); const { setModal } = useModalStore();
@ -29,83 +36,86 @@ export default function CollectionCard({ collection, className }: Props) {
} }
); );
const [expandDropdown, setExpandDropdown] = useState(false); const [expandDropdown, setExpandDropdown] = useState<DropdownTrigger>(false);
const permissions = usePermissions(collection.id as number); const permissions = usePermissions(collection.id as number);
return ( return (
<div <>
style={{
backgroundImage: `linear-gradient(45deg, ${collection.color}30 10%, ${
theme === "dark" ? "#262626" : "#f3f4f6"
} 50%, ${theme === "dark" ? "#262626" : "#f9fafb"} 100%)`,
}}
className={`border border-solid border-sky-100 dark:border-neutral-700 self-stretch min-h-[12rem] rounded-2xl shadow duration-100 hover:shadow-none hover:opacity-80 group relative ${
className || ""
}`}
>
<div <div
onClick={() => setExpandDropdown(!expandDropdown)} style={{
id={"expand-dropdown" + collection.id} backgroundImage: `linear-gradient(45deg, ${collection.color}30 10%, ${
className="inline-flex absolute top-5 right-5 rounded-md cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-1" theme === "dark" ? "#262626" : "#f3f4f6"
} 50%, ${theme === "dark" ? "#262626" : "#f9fafb"} 100%)`,
}}
className={`border border-solid border-sky-100 dark:border-neutral-700 self-stretch min-h-[12rem] rounded-2xl shadow duration-100 hover:shadow-none hover:opacity-80 group relative ${
className || ""
}`}
> >
<FontAwesomeIcon <div
icon={faEllipsis} onClick={(e) => setExpandDropdown({ x: e.clientX, y: e.clientY })}
id={"expand-dropdown" + collection.id} id={"expand-dropdown" + collection.id}
className="w-5 h-5 text-gray-500 dark:text-gray-300" className="inline-flex absolute top-5 right-5 rounded-md cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-1"
/> >
</div> <FontAwesomeIcon
<Link icon={faEllipsis}
href={`/collections/${collection.id}`} id={"expand-dropdown" + collection.id}
className="flex flex-col gap-2 justify-between min-h-[12rem] h-full select-none p-5" className="w-5 h-5 text-gray-500 dark:text-gray-300"
> />
<p className="text-2xl capitalize text-black dark:text-white break-words line-clamp-3 w-4/5">
{collection.name}
</p>
<div className="flex justify-between items-center">
<div className="flex items-center w-full">
{collection.members
.sort((a, b) => (a.userId as number) - (b.userId as number))
.map((e, i) => {
return (
<ProfilePhoto
key={i}
src={e.user.image ? e.user.image : undefined}
className="-mr-3 border-[3px]"
/>
);
})
.slice(0, 4)}
{collection.members.length - 4 > 0 ? (
<div className="h-10 w-10 text-white flex items-center justify-center rounded-full border-[3px] bg-sky-600 dark:bg-sky-600 border-slate-200 dark:border-neutral-700 -mr-3">
+{collection.members.length - 4}
</div>
) : null}
</div>
<div className="text-right w-40">
<div className="text-black dark:text-white font-bold text-sm flex justify-end gap-1 items-center">
{collection.isPublic ? (
<FontAwesomeIcon
icon={faGlobe}
title="This collection is being shared publicly."
className="w-4 h-4 drop-shadow text-gray-500 dark:text-gray-300"
/>
) : undefined}
<FontAwesomeIcon
icon={faLink}
className="w-5 h-5 text-gray-500 dark:text-gray-300"
/>
{collection._count && collection._count.links}
</div>
<div className="flex items-center justify-end gap-1 text-gray-500 dark:text-gray-300">
<FontAwesomeIcon icon={faCalendarDays} className="w-4 h-4" />
<p className="font-bold text-xs">{formattedDate}</p>
</div>
</div>
</div> </div>
</Link> <Link
href={`/collections/${collection.id}`}
className="flex flex-col gap-2 justify-between min-h-[12rem] h-full select-none p-5"
>
<p className="text-2xl capitalize text-black dark:text-white break-words line-clamp-3 w-4/5">
{collection.name}
</p>
<div className="flex justify-between items-center">
<div className="flex items-center w-full">
{collection.members
.sort((a, b) => (a.userId as number) - (b.userId as number))
.map((e, i) => {
return (
<ProfilePhoto
key={i}
src={e.user.image ? e.user.image : undefined}
className="-mr-3 border-[3px]"
/>
);
})
.slice(0, 4)}
{collection.members.length - 4 > 0 ? (
<div className="h-10 w-10 text-white flex items-center justify-center rounded-full border-[3px] bg-sky-600 dark:bg-sky-600 border-slate-200 dark:border-neutral-700 -mr-3">
+{collection.members.length - 4}
</div>
) : null}
</div>
<div className="text-right w-40">
<div className="text-black dark:text-white font-bold text-sm flex justify-end gap-1 items-center">
{collection.isPublic ? (
<FontAwesomeIcon
icon={faGlobe}
title="This collection is being shared publicly."
className="w-4 h-4 drop-shadow text-gray-500 dark:text-gray-300"
/>
) : undefined}
<FontAwesomeIcon
icon={faLink}
className="w-5 h-5 text-gray-500 dark:text-gray-300"
/>
{collection._count && collection._count.links}
</div>
<div className="flex items-center justify-end gap-1 text-gray-500 dark:text-gray-300">
<FontAwesomeIcon icon={faCalendarDays} className="w-4 h-4" />
<p className="font-bold text-xs">{formattedDate}</p>
</div>
</div>
</div>
</Link>
</div>
{expandDropdown ? ( {expandDropdown ? (
<Dropdown <Dropdown
points={{ x: expandDropdown.x, y: expandDropdown.y }}
items={[ items={[
permissions === true permissions === true
? { ? {
@ -161,9 +171,9 @@ export default function CollectionCard({ collection, className }: Props) {
if (target.id !== "expand-dropdown" + collection.id) if (target.id !== "expand-dropdown" + collection.id)
setExpandDropdown(false); setExpandDropdown(false);
}} }}
className="absolute top-[3.2rem] right-5 z-10 w-fit" className="w-fit"
/> />
) : null} ) : null}
</div> </>
); );
} }

View File

@ -19,9 +19,9 @@ type Props = {
onClickOutside: Function; onClickOutside: Function;
className?: string; className?: string;
items: MenuItem[]; items: MenuItem[];
points: { x: number; y: number }; points?: { x: number; y: number };
style?: React.CSSProperties; style?: React.CSSProperties;
width: number; // in rem width?: number; // in rem
}; };
export default function Dropdown({ export default function Dropdown({
@ -33,6 +33,7 @@ export default function Dropdown({
}: Props) { }: Props) {
const [pos, setPos] = useState<{ x: number; y: number }>(); const [pos, setPos] = useState<{ x: number; y: number }>();
const [dropdownHeight, setDropdownHeight] = useState<number>(); const [dropdownHeight, setDropdownHeight] = useState<number>();
const [dropdownWidth, setDropdownWidth] = useState<number>();
function convertRemToPixels(rem: number) { function convertRemToPixels(rem: number) {
return ( return (
@ -41,48 +42,46 @@ export default function Dropdown({
} }
useEffect(() => { useEffect(() => {
const dropdownWidth = convertRemToPixels(width); if (points) {
let finalX = points.x;
let finalY = points.y;
let finalX = points.x; // Check for x-axis overflow (left side)
let finalY = points.y; if (dropdownWidth && points.x + dropdownWidth > window.innerWidth) {
finalX = points.x - dropdownWidth;
}
// Check for x-axis overflow (left side) // Check for y-axis overflow (bottom side)
if (points.x + dropdownWidth > window.innerWidth) { if (dropdownHeight && points.y + dropdownHeight > window.innerHeight) {
finalX = points.x - dropdownWidth; finalY =
window.innerHeight -
(dropdownHeight + (window.innerHeight - points.y));
}
setPos({ x: finalX, y: finalY });
} }
// Check for y-axis overflow (bottom side)
if (dropdownHeight && points.y + dropdownHeight > window.innerHeight) {
finalY =
window.innerHeight - (dropdownHeight + (window.innerHeight - points.y));
}
setPos({ x: finalX, y: finalY });
}, [points, width, dropdownHeight]); }, [points, width, dropdownHeight]);
useEffect(() => {
const dropdownWidth = convertRemToPixels(width);
if (points.x + dropdownWidth > window.innerWidth) {
setPos({ x: points.x - dropdownWidth, y: points.y });
} else setPos(points);
}, [points, width]);
return ( return (
pos && ( (!points || pos) && (
<ClickAwayHandler <ClickAwayHandler
onMount={(e) => { onMount={(e) => {
setDropdownHeight(e.height); setDropdownHeight(e.height);
setDropdownWidth(e.width);
}} }}
style={{ style={
position: "fixed", points
top: `${pos?.y}px`, ? {
left: `${pos?.x}px`, position: "fixed",
}} top: `${pos?.y}px`,
left: `${pos?.x}px`,
}
: undefined
}
onClickOutside={onClickOutside} onClickOutside={onClickOutside}
className={`${ className={`${
className || "" className || ""
} py-1 shadow-md border border-sky-100 dark:border-neutral-700 bg-gray-50 dark:bg-neutral-800 rounded-md flex flex-col z-20 w-[${width}rem]`} } py-1 shadow-md border border-sky-100 dark:border-neutral-700 bg-gray-50 dark:bg-neutral-800 rounded-md flex flex-col z-20`}
> >
{items.map((e, i) => { {items.map((e, i) => {
const inner = e && ( const inner = e && (

View File

@ -71,7 +71,7 @@ export default function LinkCard({ link, count, className }: Props) {
); );
}, [collections, links]); }, [collections, links]);
const { removeLink, updateLink } = useLinkStore(); const { removeLink, updateLink, getLink } = useLinkStore();
const pinLink = async () => { const pinLink = async () => {
const isAlreadyPinned = link?.pinnedBy && link.pinnedBy[0]; const isAlreadyPinned = link?.pinnedBy && link.pinnedBy[0];
@ -92,7 +92,7 @@ export default function LinkCard({ link, count, className }: Props) {
}; };
const updateArchive = async () => { const updateArchive = async () => {
const load = toast.loading("Applying..."); const load = toast.loading("Sending request...");
setExpandDropdown(false); setExpandDropdown(false);
@ -104,8 +104,10 @@ export default function LinkCard({ link, count, className }: Props) {
toast.dismiss(load); toast.dismiss(load);
if (response.ok) toast.success(`Link is being archived.`); if (response.ok) {
else toast.error(data); toast.success(`Link is being archived...`);
getLink(link.id as number);
} else toast.error(data);
}; };
const deleteLink = async () => { const deleteLink = async () => {
@ -131,98 +133,100 @@ export default function LinkCard({ link, count, className }: Props) {
); );
return ( return (
<div <>
className={`h-fit border border-solid border-sky-100 dark:border-neutral-700 bg-gradient-to-tr from-slate-200 dark:from-neutral-800 from-10% to-gray-50 dark:to-[#303030] via-20% shadow hover:shadow-none duration-100 rounded-2xl relative group ${
className || ""
}`}
>
{(permissions === true ||
permissions?.canUpdate ||
permissions?.canDelete) && (
<div
onClick={(e) => {
setExpandDropdown({ x: e.clientX, y: e.clientY });
}}
id={"expand-dropdown" + link.id}
className="text-gray-500 dark:text-gray-300 inline-flex rounded-md cursor-pointer hover:bg-slate-200 dark:hover:bg-neutral-700 absolute right-5 top-5 z-10 duration-100 p-1"
>
<FontAwesomeIcon
icon={faEllipsis}
title="More"
className="w-5 h-5"
id={"expand-dropdown" + link.id}
/>
</div>
)}
<div <div
onClick={() => { className={`h-fit border border-solid border-sky-100 dark:border-neutral-700 bg-gradient-to-tr from-slate-200 dark:from-neutral-800 from-10% to-gray-50 dark:to-[#303030] via-20% shadow hover:shadow-none duration-100 rounded-2xl relative group ${
setModal({ className || ""
modal: "LINK", }`}
state: true,
method: "UPDATE",
isOwnerOrMod:
permissions === true || (permissions?.canUpdate as boolean),
active: link,
});
}}
className="flex items-start cursor-pointer gap-5 sm:gap-10 h-full w-full p-5"
> >
{url && ( {(permissions === true ||
<Image permissions?.canUpdate ||
src={`https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${url.origin}&size=32`} permissions?.canDelete) && (
width={64} <div
height={64} onClick={(e) => {
alt="" setExpandDropdown({ x: e.clientX, y: e.clientY });
className="blur-sm absolute w-16 group-hover:opacity-80 duration-100 rounded-2xl bottom-5 right-5 opacity-60 select-none"
draggable="false"
onError={(e) => {
const target = e.target as HTMLElement;
target.style.display = "none";
}} }}
/> id={"expand-dropdown" + link.id}
className="text-gray-500 dark:text-gray-300 inline-flex rounded-md cursor-pointer hover:bg-slate-200 dark:hover:bg-neutral-700 absolute right-5 top-5 z-10 duration-100 p-1"
>
<FontAwesomeIcon
icon={faEllipsis}
title="More"
className="w-5 h-5"
id={"expand-dropdown" + link.id}
/>
</div>
)} )}
<div className="flex justify-between gap-5 w-full h-full z-0"> <div
<div className="flex flex-col justify-between w-full"> onClick={() => {
<div className="flex items-baseline gap-1"> setModal({
<p className="text-sm text-gray-500 dark:text-gray-300"> modal: "LINK",
{count + 1} state: true,
</p> method: "UPDATE",
<p className="text-lg text-black dark:text-white truncate capitalize w-full pr-8"> isOwnerOrMod:
{unescapeString(link.name || link.description)} permissions === true || (permissions?.canUpdate as boolean),
</p> active: link,
</div> });
<Link }}
href={`/collections/${link.collection.id}`} className="flex items-start cursor-pointer gap-5 sm:gap-10 h-full w-full p-5"
onClick={(e) => { >
e.stopPropagation(); {url && (
<Image
src={`https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${url.origin}&size=32`}
width={64}
height={64}
alt=""
className="blur-sm absolute w-16 group-hover:opacity-80 duration-100 rounded-2xl bottom-5 right-5 opacity-60 select-none"
draggable="false"
onError={(e) => {
const target = e.target as HTMLElement;
target.style.display = "none";
}} }}
className="flex items-center gap-1 max-w-full w-fit my-3 hover:opacity-70 duration-100" />
> )}
<FontAwesomeIcon
icon={faFolder} <div className="flex justify-between gap-5 w-full h-full z-0">
className="w-4 h-4 mt-1 drop-shadow" <div className="flex flex-col justify-between w-full">
style={{ color: collection?.color }} <div className="flex items-baseline gap-1">
/> <p className="text-sm text-gray-500 dark:text-gray-300">
<p className="text-black dark:text-white truncate capitalize w-full"> {count + 1}
{collection?.name} </p>
</p> <p className="text-lg text-black dark:text-white truncate capitalize w-full pr-8">
</Link> {unescapeString(link.name || link.description)}
<Link </p>
href={link.url} </div>
target="_blank" <Link
onClick={(e) => { href={`/collections/${link.collection.id}`}
e.stopPropagation(); onClick={(e) => {
}} e.stopPropagation();
className="flex items-center gap-1 max-w-full w-fit text-gray-500 dark:text-gray-300 hover:opacity-70 duration-100" }}
> className="flex items-center gap-1 max-w-full w-fit my-3 hover:opacity-70 duration-100"
<FontAwesomeIcon icon={faLink} className="mt-1 w-4 h-4" /> >
<p className="truncate w-full">{shortendURL}</p> <FontAwesomeIcon
</Link> icon={faFolder}
<div className="flex items-center gap-1 text-gray-500 dark:text-gray-300"> className="w-4 h-4 mt-1 drop-shadow"
<FontAwesomeIcon icon={faCalendarDays} className="w-4 h-4" /> style={{ color: collection?.color }}
<p>{formattedDate}</p> />
<p className="text-black dark:text-white truncate capitalize w-full">
{collection?.name}
</p>
</Link>
<Link
href={link.url}
target="_blank"
onClick={(e) => {
e.stopPropagation();
}}
className="flex items-center gap-1 max-w-full w-fit text-gray-500 dark:text-gray-300 hover:opacity-70 duration-100"
>
<FontAwesomeIcon icon={faLink} className="mt-1 w-4 h-4" />
<p className="truncate w-full">{shortendURL}</p>
</Link>
<div className="flex items-center gap-1 text-gray-500 dark:text-gray-300">
<FontAwesomeIcon icon={faCalendarDays} className="w-4 h-4" />
<p>{formattedDate}</p>
</div>
</div> </div>
</div> </div>
</div> </div>
@ -275,9 +279,9 @@ export default function LinkCard({ link, count, className }: Props) {
if (target.id !== "expand-dropdown" + link.id) if (target.id !== "expand-dropdown" + link.id)
setExpandDropdown(false); setExpandDropdown(false);
}} }}
width={10} className="w-40"
/> />
) : null} ) : null}
</div> </>
); );
} }

View File

@ -23,15 +23,49 @@ import {
import isValidUrl from "@/lib/client/isValidUrl"; import isValidUrl from "@/lib/client/isValidUrl";
import { useTheme } from "next-themes"; import { useTheme } from "next-themes";
import unescapeString from "@/lib/client/unescapeString"; import unescapeString from "@/lib/client/unescapeString";
import useLinkStore from "@/store/links";
type Props = { type Props = {
link: LinkIncludingShortenedCollectionAndTags; linkId: number;
isOwnerOrMod: boolean; isOwnerOrMod: boolean;
}; };
export default function LinkDetails({ link, isOwnerOrMod }: Props) { export default function LinkDetails({ linkId, isOwnerOrMod }: Props) {
const { theme } = useTheme(); const { theme } = useTheme();
const { links, getLink } = useLinkStore();
const [link, setLink] = useState<LinkIncludingShortenedCollectionAndTags>(
links.find(
(e) => e.id === linkId
) as LinkIncludingShortenedCollectionAndTags
);
useEffect(() => {
setLink(
links.find(
(e) => e.id === linkId
) as LinkIncludingShortenedCollectionAndTags
);
}, [links]);
useEffect(() => {
let interval: NodeJS.Timer | undefined;
if (link.screenshotPath === "pending" || link.pdfPath === "pending") {
interval = setInterval(() => getLink(link.id as number), 5000);
} else {
if (interval) {
clearInterval(interval);
}
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [link.screenshotPath, link.pdfPath]);
const [imageError, setImageError] = useState<boolean>(false); const [imageError, setImageError] = useState<boolean>(false);
const formattedDate = new Date(link.createdAt as string).toLocaleString( const formattedDate = new Date(link.createdAt as string).toLocaleString(
"en-US", "en-US",
@ -59,6 +93,14 @@ export default function LinkDetails({ link, isOwnerOrMod }: Props) {
); );
}, [collections]); }, [collections]);
useEffect(() => {
setCollection(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
}, [collections]);
const [colorPalette, setColorPalette] = useState<RGBColor[]>(); const [colorPalette, setColorPalette] = useState<RGBColor[]>();
const colorThief = new ColorThief(); const colorThief = new ColorThief();

View File

@ -64,7 +64,10 @@ export default function LinkModal({
<Tab.Panels> <Tab.Panels>
{activeLink && method === "UPDATE" && ( {activeLink && method === "UPDATE" && (
<Tab.Panel> <Tab.Panel>
<LinkDetails link={activeLink} isOwnerOrMod={isOwnerOrMod} /> <LinkDetails
linkId={activeLink.id as number}
isOwnerOrMod={isOwnerOrMod}
/>
</Tab.Panel> </Tab.Panel>
)} )}
@ -73,7 +76,9 @@ export default function LinkModal({
<AddOrEditLink <AddOrEditLink
toggleLinkModal={toggleLinkModal} toggleLinkModal={toggleLinkModal}
method="UPDATE" method="UPDATE"
activeLink={activeLink} activeLink={
activeLink as LinkIncludingShortenedCollectionAndTags
}
/> />
) : ( ) : (
<AddOrEditLink <AddOrEditLink

View File

@ -21,7 +21,7 @@ export default function SortDropdown({
const target = e.target as HTMLInputElement; const target = e.target as HTMLInputElement;
if (target.id !== "sort-dropdown") toggleSortDropdown(); if (target.id !== "sort-dropdown") toggleSortDropdown();
}} }}
className="absolute top-8 right-0 border border-sky-100 dark:border-neutral-700 shadow-md bg-gray-50 dark:bg-neutral-800 rounded-md p-2 z-20 w-48" className="absolute top-8 right-0 border border-sky-100 dark:border-neutral-700 shadow-md bg-gray-50 dark:bg-neutral-800 rounded-md p-2 z-20 w-52"
> >
<p className="mb-2 text-black dark:text-white text-center font-semibold"> <p className="mb-2 text-black dark:text-white text-center font-semibold">
Sort by Sort by

View File

@ -14,13 +14,29 @@ export default async function archive(
}, },
}); });
// const checkExistingLink = await prisma.link.findFirst({
// where: {
// id: linkId,
// OR: [
// {
// screenshotPath: "pending",
// },
// {
// pdfPath: "pending",
// },
// ],
// },
// });
// if (checkExistingLink) return "A request has already been made.";
const link = await prisma.link.update({ const link = await prisma.link.update({
where: { where: {
id: linkId, id: linkId,
}, },
data: { data: {
screenshotPath: "pending", screenshotPath: user?.archiveAsScreenshot ? "pending" : null,
pdfPath: "pending", pdfPath: user?.archiveAsPDF ? "pending" : null,
}, },
}); });
@ -88,8 +104,8 @@ export default async function archive(
await browser.close(); await browser.close();
} catch (err) { } catch (err) {
console.log(err);
await browser.close(); await browser.close();
return err;
} }
} }
} }

View File

@ -0,0 +1,48 @@
import { prisma } from "@/lib/api/db";
import { Collection, Link, UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission";
export default async function getLinkById(userId: number, linkId: number) {
if (!linkId)
return {
response: "Please choose a valid link.",
status: 401,
};
const collectionIsAccessible = (await getPermission({ userId, linkId })) as
| (Collection & {
members: UsersAndCollections[];
})
| null;
const memberHasAccess = collectionIsAccessible?.members.some(
(e: UsersAndCollections) => e.userId === userId && e.canUpdate
);
const isCollectionOwner = collectionIsAccessible?.ownerId === userId;
if (collectionIsAccessible?.ownerId !== userId && !memberHasAccess)
return {
response: "Collection is not accessible.",
status: 401,
};
else {
const updatedLink = await prisma.link.findUnique({
where: {
id: linkId,
},
include: {
tags: true,
collection: true,
pinnedBy: isCollectionOwner
? {
where: { id: userId },
select: { id: true },
}
: undefined,
},
});
return { response: updatedLink, status: 200 };
}
}

View File

@ -4,7 +4,7 @@ import { Collection, Link, UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission"; import getPermission from "@/lib/api/getPermission";
import moveFile from "@/lib/api/storage/moveFile"; import moveFile from "@/lib/api/storage/moveFile";
export default async function updateLink( export default async function updateLinkById(
userId: number, userId: number,
linkId: number, linkId: number,
data: LinkIncludingShortenedCollectionAndTags data: LinkIncludingShortenedCollectionAndTags

View File

@ -3,6 +3,7 @@ import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/v1/auth/[...nextauth]"; import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import deleteLinkById from "@/lib/api/controllers/links/linkId/deleteLinkById"; import deleteLinkById from "@/lib/api/controllers/links/linkId/deleteLinkById";
import updateLinkById from "@/lib/api/controllers/links/linkId/updateLinkById"; import updateLinkById from "@/lib/api/controllers/links/linkId/updateLinkById";
import getLinkById from "@/lib/api/controllers/links/linkId/getLinkById";
export default async function links(req: NextApiRequest, res: NextApiResponse) { export default async function links(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions); const session = await getServerSession(req, res, authOptions);
@ -15,7 +16,12 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
"You are not a subscriber, feel free to reach out to us at support@linkwarden.app in case of any issues.", "You are not a subscriber, feel free to reach out to us at support@linkwarden.app in case of any issues.",
}); });
if (req.method === "PUT") { if (req.method === "GET") {
const updated = await getLinkById(session.user.id, Number(req.query.id));
return res.status(updated.status).json({
response: updated.response,
});
} else if (req.method === "PUT") {
const updated = await updateLinkById( const updated = await updateLinkById(
session.user.id, session.user.id,
Number(req.query.id), Number(req.query.id),

View File

@ -17,6 +17,7 @@ type LinkStore = {
addLink: ( addLink: (
body: LinkIncludingShortenedCollectionAndTags body: LinkIncludingShortenedCollectionAndTags
) => Promise<ResponseObject>; ) => Promise<ResponseObject>;
getLink: (linkId: number) => Promise<ResponseObject>;
updateLink: ( updateLink: (
link: LinkIncludingShortenedCollectionAndTags link: LinkIncludingShortenedCollectionAndTags
) => Promise<ResponseObject>; ) => Promise<ResponseObject>;
@ -65,6 +66,21 @@ const useLinkStore = create<LinkStore>()((set) => ({
return { ok: response.ok, data: data.response }; return { ok: response.ok, data: data.response };
}, },
getLink: async (linkId) => {
const response = await fetch(`/api/v1/links/${linkId}`);
const data = await response.json();
if (response.ok) {
set((state) => ({
links: state.links.map((e) =>
e.id === data.response.id ? data.response : e
),
}));
}
return { ok: response.ok, data: data.response };
},
updateLink: async (link) => { updateLink: async (link) => {
const response = await fetch(`/api/v1/links/${link.id}`, { const response = await fetch(`/api/v1/links/${link.id}`, {
body: JSON.stringify(link), body: JSON.stringify(link),