Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

bug fix + cleaner code/logic

Daniel4b9b1be80c43
diff --git a/hooks/useLinks.tsx b/hooks/useLinks.tsx
index de52f098..e03999d6 100644
--- a/hooks/useLinks.tsx
+++ b/hooks/useLinks.tsx
@@ -4,41 +4,38 @@ import useDetectPageBottom from "./useDetectPageBottom";
import { useRouter } from "next/router";
import useLinkStore from "@/store/links";
-export default function useLinks({
- sort,
- searchFilter,
- searchQuery,
- pinnedOnly,
- collectionId,
- tagId,
-}: Omit<LinkRequestQuery, "cursor"> = {}) {
+export default function useLinks(
+ {
+ sort,
+ searchFilter,
+ searchQuery,
+ pinnedOnly,
+ collectionId,
+ tagId,
+ }: Omit<LinkRequestQuery, "cursor"> = { sort: 0 }
+) {
const { links, setLinks, resetLinks } = useLinkStore();
const router = useRouter();
const hasReachedBottom = useDetectPageBottom();
const getLinks = async (isInitialCall: boolean, cursor?: number) => {
+ const requestBody: LinkRequestQuery = {
+ cursor,
+ sort,
+ searchFilter,
+ searchQuery,
+ pinnedOnly,
+ collectionId,
+ tagId,
+ };
+
+ const encodedData = encodeURIComponent(JSON.stringify(requestBody));
+
+ console.log(encodedData);
+
const response = await fetch(
- `/api/routes/links?cursor=${cursor}${
- (sort ? "&sort=" + sort : "") +
- (searchQuery && searchFilter
- ? "&searchQuery=" +
- searchQuery +
- "&searchFilter=" +
- searchFilter.name +
- "-" +
- searchFilter.url +
- "-" +
- searchFilter.description +
- "-" +
- searchFilter.collection +
- "-" +
- searchFilter.tags
- : "") +
- (collectionId ? "&collectionId=" + collectionId : "") +
- (tagId ? "&tagId=" + tagId : "") +
- (pinnedOnly ? "&pinnedOnly=" + pinnedOnly : "")
- }`
+ `/api/routes/links?body=${encodeURIComponent(encodedData)}`
);
const data = await response.json();
diff --git a/lib/api/controllers/links/getLinks.ts b/lib/api/controllers/links/getLinks.ts
index 0a4a6134..e6a21da5 100644
--- a/lib/api/controllers/links/getLinks.ts
+++ b/lib/api/controllers/links/getLinks.ts
@@ -1,25 +1,9 @@
import { prisma } from "@/lib/api/db";
-import { LinkRequestQuery, LinkSearchFilter, Sort } from "@/types/global";
+import { LinkRequestQuery, Sort } from "@/types/global";
-export default async function getLink(userId: number, query: LinkRequestQuery) {
- query.sort = Number(query.sort) || 0;
- query.pinnedOnly = query.pinnedOnly
- ? JSON.parse(query.pinnedOnly as unknown as string)
- : undefined;
-
- if (query.searchFilter) {
- const filterParams = (query.searchFilter as unknown as string).split("-");
-
- query.searchFilter = {} as LinkSearchFilter;
-
- query.searchFilter.name = JSON.parse(filterParams[0]);
- query.searchFilter.url = JSON.parse(filterParams[1]);
- query.searchFilter.description = JSON.parse(filterParams[2]);
- query.searchFilter.collection = JSON.parse(filterParams[3]);
- query.searchFilter.tags = JSON.parse(filterParams[4]);
- }
-
- console.log(query.searchFilter);
+export default async function getLink(userId: number, body: string) {
+ const query: LinkRequestQuery = JSON.parse(decodeURIComponent(body));
+ console.log(query);
// Sorting logic
let order: any;
@@ -48,76 +32,77 @@ export default async function getLink(userId: number, query: LinkRequestQuery) {
name: "desc",
};
- const links =
- // Searching logic
- query.searchFilter && query.searchQuery
- ? await prisma.link.findMany({
- take: Number(process.env.PAGINATION_TAKE_COUNT),
- skip: query.cursor !== "undefined" ? 1 : undefined,
- cursor:
- query.cursor !== "undefined"
+ const links = await prisma.link.findMany({
+ take: Number(process.env.PAGINATION_TAKE_COUNT),
+ skip: query.cursor ? 1 : undefined,
+ cursor: query.cursor
+ ? {
+ id: query.cursor,
+ }
+ : undefined,
+ where: {
+ [query.searchQuery ? "OR" : "AND"]: [
+ {
+ pinnedBy: query.pinnedOnly ? { some: { id: userId } } : undefined,
+ },
+ {
+ name: {
+ contains: query.searchFilter?.name ? query.searchQuery : undefined,
+ mode: "insensitive",
+ },
+ },
+ {
+ url: {
+ contains: query.searchFilter?.url ? query.searchQuery : undefined,
+ mode: "insensitive",
+ },
+ },
+ {
+ description: {
+ contains: query.searchFilter?.description
+ ? query.searchQuery
+ : undefined,
+ mode: "insensitive",
+ },
+ },
+ {
+ collection: {
+ id: query.collectionId ? query.collectionId : undefined, // If collectionId was defined, filter by collection
+ name: query.searchFilter?.collection
? {
- id: Number(query.cursor),
+ contains: query.searchQuery,
+ mode: "insensitive",
}
: undefined,
- where: {
- OR: [
- {
- name: {
- contains: query.searchFilter?.name
- ? query.searchQuery
- : undefined,
- mode: "insensitive",
- },
- },
- {
- url: {
- contains: query.searchFilter?.url
- ? query.searchQuery
- : undefined,
- mode: "insensitive",
- },
- },
- {
- description: {
- contains: query.searchFilter?.description
- ? query.searchQuery
- : undefined,
- mode: "insensitive",
- },
- },
- {
- collection: {
- name: {
- contains: query.searchFilter?.collection
- ? query.searchQuery
- : undefined,
- mode: "insensitive",
+ OR: query.searchQuery
+ ? undefined
+ : [
+ {
+ ownerId: userId,
},
- OR: [
- {
- ownerId: userId,
- },
- {
- members: {
- some: {
- userId,
- },
+ {
+ members: {
+ some: {
+ userId,
},
},
- ],
- },
- },
- {
- tags: {
- // If tagId was defined, search by tag
+ },
+ ],
+ },
+ },
+ {
+ tags:
+ query.searchQuery && !query.searchFilter?.tags
+ ? undefined
+ : {
some: {
- name: {
- contains: query.searchFilter?.tags
- ? query.searchQuery
- : undefined,
- mode: "insensitive",
- },
+ id: query.tagId ? query.tagId : undefined, // If tagId was defined, filter by tag
+ name: query.searchFilter?.tags
+ ? {
+ contains: query.searchQuery,
+ mode: "insensitive",
+ }
+ : undefined,
OR: [
{ ownerId: userId }, // Tags owned by the user
{
@@ -142,88 +127,21 @@ export default async function getLink(userId: number, query: LinkRequestQuery) {
],
},
},
- },
- ],
- },
- include: {
- tags: true,
- collection: true,
- pinnedBy: {
- where: { id: userId },
- select: { id: true },
- },
- },
- orderBy: order || undefined,
- })
- : // If not searching
- await prisma.link.findMany({
- take: Number(process.env.PAGINATION_TAKE_COUNT),
- skip: query.cursor !== "undefined" ? 1 : undefined,
- cursor:
- query.cursor !== "undefined"
- ? {
- id: Number(query.cursor),
- }
- : undefined,
- where: {
- pinnedBy: query.pinnedOnly ? { some: { id: userId } } : undefined,
- collection: {
- id: query.collectionId && Number(query.collectionId), // If collectionId was defined, search by collection
-
- OR: [
- {
- ownerId: userId,
- },
- {
- members: {
- some: {
- userId,
- },
- },
- },
- ],
- },
- tags: {
- some: query.tagId // If tagId was defined, search by tag
- ? {
- id: Number(query.tagId),
- OR: [
- { ownerId: userId }, // Tags owned by the user
- {
- links: {
- some: {
- collection: {
- members: {
- some: {
- userId, // Tags from collections where the user is a member
- },
- },
- },
- },
- },
- },
- ],
- }
- : undefined,
- },
- },
- include: {
- tags: true,
- collection: {
- select: {
- id: true,
- ownerId: true,
- name: true,
- color: true,
- },
- },
- pinnedBy: {
- where: { id: userId },
- select: { id: true },
- },
- },
- orderBy: order || undefined,
- });
+ },
+ ],
+ },
+ include: {
+ tags: true,
+ collection: true,
+ pinnedBy: {
+ where: { id: userId },
+ select: { id: true },
+ },
+ },
+ orderBy: order || {
+ createdAt: "desc",
+ },
+ });
return { response: links, status: 200 };
}
diff --git a/lib/api/controllers/public/getCollection.ts b/lib/api/controllers/public/getCollection.ts
index ce883fd9..7aa26a81 100644
--- a/lib/api/controllers/public/getCollection.ts
+++ b/lib/api/controllers/public/getCollection.ts
@@ -1,7 +1,10 @@
import { prisma } from "@/lib/api/db";
import { PublicLinkRequestQuery } from "@/types/global";
-export default async function getCollection(query: PublicLinkRequestQuery) {
+export default async function getCollection(body: string) {
+ const query: PublicLinkRequestQuery = JSON.parse(decodeURIComponent(body));
+ console.log(query);
+
let data;
const collection = await prisma.collection.findFirst({
@@ -14,13 +17,12 @@ export default async function getCollection(query: PublicLinkRequestQuery) {
if (collection) {
const links = await prisma.link.findMany({
take: Number(process.env.PAGINATION_TAKE_COUNT),
- skip: query.cursor !== "undefined" ? 1 : undefined,
- cursor:
- query.cursor !== "undefined"
- ? {
- id: Number(query.cursor),
- }
- : undefined,
+ skip: query.cursor ? 1 : undefined,
+ cursor: query.cursor
+ ? {
+ id: Number(query.cursor),
+ }
+ : undefined,
where: {
collection: {
id: Number(query.collectionId),
diff --git a/lib/client/getPublicCollectionData.ts b/lib/client/getPublicCollectionData.ts
index 7aad89f7..6179142a 100644
--- a/lib/client/getPublicCollectionData.ts
+++ b/lib/client/getPublicCollectionData.ts
@@ -1,16 +1,23 @@
-import { PublicCollectionIncludingLinks } from "@/types/global";
+import {
+ PublicCollectionIncludingLinks,
+ PublicLinkRequestQuery,
+} from "@/types/global";
import { Dispatch, SetStateAction } from "react";
const getPublicCollectionData = async (
- collectionId: string,
+ collectionId: number,
prevData: PublicCollectionIncludingLinks,
setData: Dispatch<SetStateAction<PublicCollectionIncludingLinks | undefined>>
) => {
+ const requestBody: PublicLinkRequestQuery = {
+ cursor: prevData?.links?.at(-1)?.id,
+ collectionId,
+ };
+
+ const encodedData = encodeURIComponent(JSON.stringify(requestBody));
+
const res = await fetch(
- "/api/public/routes/collections?collectionId=" +
- collectionId +
- "&cursor=" +
- prevData?.links?.at(-1)?.id
+ "/api/public/routes/collections?body=" + encodeURIComponent(encodedData)
);
const data = await res.json();
diff --git a/pages/api/public/routes/collections.ts b/pages/api/public/routes/collections.ts
index 57d8adf9..5f6b808c 100644
--- a/pages/api/public/routes/collections.ts
+++ b/pages/api/public/routes/collections.ts
@@ -1,21 +1,18 @@
import getCollection from "@/lib/api/controllers/public/getCollection";
-import { PublicLinkRequestQuery } from "@/types/global";
import type { NextApiRequest, NextApiResponse } from "next";
export default async function collections(
req: NextApiRequest,
res: NextApiResponse
) {
- const query: PublicLinkRequestQuery = req.query;
-
- if (!query) {
+ if (!req?.query?.body) {
return res
.status(401)
.json({ response: "Please choose a valid collection." });
}
if (req.method === "GET") {
- const collection = await getCollection(query);
+ const collection = await getCollection(req?.query?.body as string);
return res
.status(collection.status)
.json({ response: collection.response });
diff --git a/pages/api/routes/links/index.ts b/pages/api/routes/links/index.ts
index eff2be73..4971b11d 100644
--- a/pages/api/routes/links/index.ts
+++ b/pages/api/routes/links/index.ts
@@ -14,7 +14,7 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
}
if (req.method === "GET") {
- const links = await getLinks(session.user.id, req.query);
+ const links = await getLinks(session.user.id, req?.query?.body as string);
return res.status(links.status).json({ response: links.response });
} else if (req.method === "POST") {
const newlink = await postLink(req.body, session.user.id);
diff --git a/pages/collections/[id].tsx b/pages/collections/[id].tsx
index b6659d9b..8fae6628 100644
--- a/pages/collections/[id].tsx
+++ b/pages/collections/[id].tsx
@@ -221,9 +221,11 @@ export default function Index() {
</div>
</div>
<div className="grid 2xl:grid-cols-3 xl:grid-cols-2 gap-5">
- {links.map((e, i) => {
- return <LinkCard key={i} link={e} count={i} />;
- })}
+ {links
+ .filter((e) => e.collectionId === Number(router.query.id))
+ .map((e, i) => {
+ return <LinkCard key={i} link={e} count={i} />;
+ })}
</div>
</div>
</MainLayout>
diff --git a/pages/dashboard.tsx b/pages/dashboard.tsx
index 140f8ed4..0de1dc48 100644
--- a/pages/dashboard.tsx
+++ b/pages/dashboard.tsx
@@ -35,7 +35,7 @@ export default function Dashboard() {
return storedValue ? storedValue === "true" : true;
});
- useLinks({ pinnedOnly: true });
+ useLinks({ pinnedOnly: true, sort: 0 });
useEffect(() => {
localStorage.setItem(
@@ -134,9 +134,11 @@ export default function Dashboard() {
leaveTo="transform opacity-0 -translate-y-3"
>
<Disclosure.Panel className="flex flex-col gap-5 w-full">
- {links.map((e, i) => (
- <LinkCard key={i} link={e} count={i} />
- ))}
+ {links
+ .filter((e) => e.pinnedBy)
+ .map((e, i) => (
+ <LinkCard key={i} link={e} count={i} />
+ ))}
</Disclosure.Panel>
</Transition>
</div>
diff --git a/pages/public/collections/[id].tsx b/pages/public/collections/[id].tsx
index d2d45be8..f6977766 100644
--- a/pages/public/collections/[id].tsx
+++ b/pages/public/collections/[id].tsx
@@ -14,7 +14,7 @@ export default function PublicCollections() {
useEffect(() => {
if (router.query.id) {
getPublicCollectionData(
- router.query.id as string,
+ Number(router.query.id),
data as PublicCollectionIncludingLinks,
setData
);
@@ -33,7 +33,7 @@ export default function PublicCollections() {
useEffect(() => {
if (hasReachedBottom && router.query.id) {
getPublicCollectionData(
- router.query.id as string,
+ Number(router.query.id),
data as PublicCollectionIncludingLinks,
setData
);
diff --git a/pages/tags/[id].tsx b/pages/tags/[id].tsx
index c85040fd..b3a021ec 100644
--- a/pages/tags/[id].tsx
+++ b/pages/tags/[id].tsx
@@ -67,9 +67,11 @@ export default function Index() {
</div>
</div>
<div className="grid 2xl:grid-cols-3 xl:grid-cols-2 gap-5">
- {links.map((e, i) => {
- return <LinkCard key={i} link={e} count={i} />;
- })}
+ {links
+ .filter((e) => e.tags.some((e) => e.id === Number(router.query.id)))
+ .map((e, i) => {
+ return <LinkCard key={i} link={e} count={i} />;
+ })}
</div>
</div>
</MainLayout>
diff --git a/types/global.ts b/types/global.ts
index 8c0672a9..8c9d106e 100644
--- a/types/global.ts
+++ b/types/global.ts
@@ -66,16 +66,16 @@ export type LinkSearchFilter = {
};
export type LinkRequestQuery = {
- cursor?: string;
+ cursor?: number;
collectionId?: number;
tagId?: number;
- sort?: Sort;
+ sort: Sort;
searchFilter?: LinkSearchFilter;
searchQuery?: string;
pinnedOnly?: boolean;
};
export type PublicLinkRequestQuery = {
- cursor?: string;
- collectionId?: number;
+ cursor?: number;
+ collectionId: number;
};