Skip to content

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

implement the meilisearch for the public page

daniel31x13bc013e781979
diff --git a/hooks/store/publicLinks.tsx b/hooks/store/publicLinks.tsx
index dff349d1..71b88251 100644
--- a/hooks/store/publicLinks.tsx
+++ b/hooks/store/publicLinks.tsx
@@ -1,8 +1,4 @@
-import {
- InfiniteData,
- useInfiniteQuery,
- UseInfiniteQueryResult,
-} from "@tanstack/react-query";
+import { useInfiniteQuery } from "@tanstack/react-query";
import { useMemo } from "react";
import {
LinkIncludingShortenedCollectionAndTags,
@@ -32,23 +28,20 @@ const usePublicLinks = (params: LinkRequestQuery = {}) => {
const { data, ...rest } = useFetchLinks(queryString);
const links = useMemo(() => {
- return data?.pages.reduce((acc, page) => {
- return [...acc, ...page];
- }, []);
+ return data?.pages?.flatMap((page) => page?.links ?? []) ?? [];
}, [data]);
+ const memoizedData = useMemo(() => ({ ...data, ...rest }), [data, rest]);
+
return {
links,
- data: { ...data, ...rest },
- } as {
- links: LinkIncludingShortenedCollectionAndTags[];
- data: UseInfiniteQueryResult<InfiniteData<any, unknown>, Error>;
+ data: memoizedData,
};
};
const useFetchLinks = (params: string) => {
return useInfiniteQuery({
- queryKey: ["links", { params }],
+ queryKey: ["publicLinks", { params }],
queryFn: async (params) => {
const response = await fetch(
"/api/v1/public/collections/links?cursor=" +
@@ -57,18 +50,20 @@ const useFetchLinks = (params: string) => {
? "&" + (params.queryKey[1] as any).params
: "")
);
-
const data = await response.json();
- return data.response;
+ return {
+ links: data.data.links as LinkIncludingShortenedCollectionAndTags[],
+ nextCursor: data.data.nextCursor as number | null,
+ };
},
initialPageParam: 0,
refetchOnWindowFocus: false,
getNextPageParam: (lastPage) => {
- if (lastPage.length === 0) {
+ if (lastPage.nextCursor === null) {
return undefined;
}
- return lastPage.at(-1).id;
+ return lastPage.nextCursor;
},
});
};
diff --git a/lib/api/controllers/public/links/getPublicLinksUnderCollection.ts b/lib/api/controllers/public/links/getPublicLinksUnderCollection.ts
deleted file mode 100644
index e6b8f9c6..00000000
--- a/lib/api/controllers/public/links/getPublicLinksUnderCollection.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { prisma } from "@/lib/api/db";
-import { LinkRequestQuery, Order, Sort } from "@/types/global";
-
-export default async function getLink(query: LinkRequestQuery) {
- const POSTGRES_IS_ENABLED =
- process.env.DATABASE_URL?.startsWith("postgresql");
-
- let order: Order = { id: "desc" };
- if (query.sort === Sort.DateNewestFirst) order = { id: "desc" };
- else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" };
- else if (query.sort === Sort.NameAZ) order = { name: "asc" };
- else if (query.sort === Sort.NameZA) order = { name: "desc" };
-
- const searchConditions = [];
-
- if (query.searchQueryString) {
- searchConditions.push({
- name: {
- contains: query.searchQueryString,
- mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined,
- },
- });
-
- searchConditions.push({
- url: {
- contains: query.searchQueryString,
- mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined,
- },
- });
-
- searchConditions.push({
- description: {
- contains: query.searchQueryString,
- mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined,
- },
- });
-
- searchConditions.push({
- tags: {
- some: {
- name: {
- contains: query.searchQueryString,
- mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined,
- },
- },
- },
- });
- }
-
- const links = await prisma.link.findMany({
- take: Number(process.env.PAGINATION_TAKE_COUNT) || 50,
- skip: query.cursor ? 1 : undefined,
- cursor: query.cursor ? { id: query.cursor } : undefined,
- where: {
- collection: {
- id: query.collectionId,
- isPublic: true,
- },
- [query.searchQueryString ? "OR" : "AND"]: [...searchConditions],
- },
- include: {
- tags: true,
- },
- orderBy: order || { id: "desc" },
- });
-
- return { response: links, status: 200 };
-}
diff --git a/lib/api/controllers/search/searchLinks.ts b/lib/api/controllers/search/searchLinks.ts
index f7fc3148..5cfd04ef 100644
--- a/lib/api/controllers/search/searchLinks.ts
+++ b/lib/api/controllers/search/searchLinks.ts
@@ -7,10 +7,17 @@ import {
parseSearchTokens,
} from "../../searchQueryBuilder";
-export default async function searchLinks(
- userId: number,
- query: LinkRequestQuery
-) {
+interface SearchLinksParams {
+ query: LinkRequestQuery;
+ userId?: number;
+ publicOnly?: boolean;
+}
+
+export default async function searchLinks({
+ query,
+ userId,
+ publicOnly,
+}: SearchLinksParams) {
const POSTGRES_IS_ENABLED =
process.env.DATABASE_URL?.startsWith("postgresql");
@@ -32,21 +39,27 @@ export default async function searchLinks(
}
const collectionCondition = [];
- if (query.collectionId) {
+ if (query.collectionId || publicOnly) {
collectionCondition.push({
- collection: { id: query.collectionId },
+ collection: {
+ id: query.collectionId,
+ ...(publicOnly ? { isPublic: true } : {}),
+ },
});
}
- const pinnedCondition = query.pinnedOnly
- ? { pinnedBy: { some: { id: userId } } }
- : {};
+ const pinnedCondition =
+ query.pinnedOnly && userId ? { pinnedBy: { some: { id: userId } } } : {};
if (meiliClient && query.searchQueryString) {
const tokens = parseSearchTokens(query.searchQueryString);
const meiliQuery = buildMeiliQuery(tokens);
- const meiliFilters = buildMeiliFilters(tokens, userId);
+ const meiliFilters = buildMeiliFilters({
+ tokens,
+ userId,
+ publicOnly,
+ });
const limit = paginationTakeCount;
const offset = query.cursor || 0;
@@ -83,18 +96,22 @@ export default async function searchLinks(
where: {
id: { in: meiliIds },
AND: [
- {
- collection: {
- OR: [
- { ownerId: userId },
+ ...(userId
+ ? [
{
- members: {
- some: { userId },
+ collection: {
+ OR: [
+ { ownerId: userId },
+ {
+ members: {
+ some: { userId },
+ },
+ },
+ ],
},
},
- ],
- },
- },
+ ]
+ : []),
...collectionCondition,
{
OR: [
@@ -109,10 +126,12 @@ export default async function searchLinks(
include: {
tags: true,
collection: true,
- pinnedBy: {
- where: { id: userId },
- select: { id: true },
- },
+ pinnedBy: userId
+ ? {
+ where: { id: userId },
+ select: { id: true },
+ }
+ : undefined,
},
orderBy: order,
});
@@ -162,20 +181,6 @@ export default async function searchLinks(
contains: query.searchQueryString,
mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined,
},
- OR: [
- { ownerId: userId },
- {
- links: {
- some: {
- collection: {
- members: {
- some: { userId },
- },
- },
- },
- },
- },
- ],
},
},
});
@@ -187,18 +192,22 @@ export default async function searchLinks(
cursor: query.cursor ? { id: query.cursor } : undefined,
where: {
AND: [
- {
- collection: {
- OR: [
- { ownerId: userId },
+ ...(userId
+ ? [
{
- members: {
- some: { userId },
+ collection: {
+ OR: [
+ { ownerId: userId },
+ {
+ members: {
+ some: { userId },
+ },
+ },
+ ],
},
},
- ],
- },
- },
+ ]
+ : []),
...collectionCondition,
{
OR: [
@@ -216,10 +225,12 @@ export default async function searchLinks(
include: {
tags: true,
collection: true,
- pinnedBy: {
- where: { id: userId },
- select: { id: true },
- },
+ pinnedBy: userId
+ ? {
+ where: { id: userId },
+ select: { id: true },
+ }
+ : undefined,
},
orderBy: order,
});
diff --git a/lib/api/searchQueryBuilder.ts b/lib/api/searchQueryBuilder.ts
index 4a85ed58..cdbcc4e0 100644
--- a/lib/api/searchQueryBuilder.ts
+++ b/lib/api/searchQueryBuilder.ts
@@ -90,10 +90,18 @@ export function buildMeiliQuery(tokens: Token[]): string {
return generalValues.join(" ");
}
-export function buildMeiliFilters(tokens: Token[], userId: number): string[] {
- const filters: string[] = [
- `(collectionOwnerId = ${userId}) OR (collectionMemberIds = ${userId})`,
- ];
+export function buildMeiliFilters({
+ tokens,
+ userId,
+ publicOnly,
+}: {
+ tokens: Token[];
+ userId?: number;
+ publicOnly?: boolean;
+}): string[] {
+ const filters: string[] = publicOnly
+ ? ["collectionIsPublic = true"]
+ : [`(collectionOwnerId = ${userId}) OR (collectionMemberIds = ${userId})`];
for (const { field, value, isNegative } of tokens) {
switch (field) {
diff --git a/pages/api/v1/public/collections/links/index.ts b/pages/api/v1/public/collections/links/index.ts
index 993acdaa..0b496f1d 100644
--- a/pages/api/v1/public/collections/links/index.ts
+++ b/pages/api/v1/public/collections/links/index.ts
@@ -1,4 +1,4 @@
-import getPublicLinksUnderCollection from "@/lib/api/controllers/public/links/getPublicLinksUnderCollection";
+import searchLinks from "@/lib/api/controllers/search/searchLinks";
import { LinkRequestQuery } from "@/types/global";
import type { NextApiRequest, NextApiResponse } from "next";
@@ -28,7 +28,11 @@ export default async function collections(
.json({ response: "Please choose a valid collection." });
}
- const links = await getPublicLinksUnderCollection(convertedData);
- return res.status(links.status).json({ response: links.response });
+ const { statusCode, ...data } = await searchLinks({
+ query: convertedData,
+ publicOnly: true,
+ });
+
+ return res.status(statusCode).json(data);
}
}
diff --git a/pages/api/v1/search/index.ts b/pages/api/v1/search/index.ts
index 9a59ee5f..e5f50dc2 100644
--- a/pages/api/v1/search/index.ts
+++ b/pages/api/v1/search/index.ts
@@ -27,7 +27,10 @@ export default async function search(
: undefined,
};
- const { statusCode, ...data } = await searchLinks(user.id, convertedData);
+ const { statusCode, ...data } = await searchLinks({
+ userId: user.id,
+ query: convertedData,
+ });
return res.status(statusCode).json(data);
}