Skip to content

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

bug fixed

daniel31x130630ea536e33
diff --git a/apps/mobile/app/(tabs)/links.tsx b/apps/mobile/app/(tabs)/links.tsx
index 69a5519e..a267e5af 100644
--- a/apps/mobile/app/(tabs)/links.tsx
+++ b/apps/mobile/app/(tabs)/links.tsx
@@ -1,11 +1,16 @@
-import { useLinks } from "@/hooks/store/links";
+import { useLinks } from "@linkwarden/router/links";
import { View, Text, StyleSheet, VirtualizedList } from "react-native";
import { Platform } from "react-native";
+import useAuthStore from "@/store/auth";
export default function HomeScreen() {
- const { links, data } = useLinks({
- sort: 0,
- });
+ const { auth } = useAuthStore();
+ const { links, data } = useLinks(
+ {
+ sort: 0,
+ },
+ auth
+ );
const getItem = (data: any, index: number) => data[index];
diff --git a/apps/mobile/hooks/store/links.ts b/apps/mobile/hooks/store/links.ts
deleted file mode 100644
index eb9a3e54..00000000
--- a/apps/mobile/hooks/store/links.ts
+++ /dev/null
@@ -1,548 +0,0 @@
-import useAuthStore from "@/store/auth";
-import {
- ArchivedFormat,
- LinkIncludingShortenedCollectionAndTags,
- LinkRequestQuery,
-} from "@/types/global";
-import {
- InfiniteData,
- useInfiniteQuery,
- UseInfiniteQueryResult,
- useQueryClient,
- useMutation,
-} from "@tanstack/react-query";
-import { useMemo } from "react";
-
-const useLinks = (params: LinkRequestQuery = {}) => {
- const queryParamsObject = {
- sort: params.sort ?? Number(window.localStorage.getItem("sortBy")) ?? 0,
- collectionId: params.collectionId,
- tagId: params.tagId,
- pinnedOnly: params.pinnedOnly,
- searchQueryString: params.searchQueryString,
- searchByName: params.searchByName,
- searchByUrl: params.searchByUrl,
- searchByDescription: params.searchByDescription,
- searchByTextContent: params.searchByTextContent,
- searchByTags: params.searchByTags,
- };
-
- const queryString = buildQueryString(queryParamsObject);
-
- const { data, ...rest } = useFetchLinks(queryString);
-
- const links = useMemo(() => {
- return data?.pages.reduce((acc, page) => {
- return [...acc, ...page];
- }, []);
- }, [data]);
-
- return {
- links,
- data: { ...data, ...rest },
- } as {
- links: LinkIncludingShortenedCollectionAndTags[];
- data: UseInfiniteQueryResult<InfiniteData<any, unknown>, Error>;
- };
-};
-
-const useFetchLinks = (params: string) => {
- const { auth } = useAuthStore();
-
- return useInfiniteQuery({
- queryKey: ["links", { params }],
- queryFn: async (params) => {
- const url =
- auth.instance +
- "/api/v1/links?cursor=" +
- params.pageParam +
- ((params.queryKey[1] as any).params
- ? "&" + (params.queryKey[1] as any).params
- : "");
-
- const response = await fetch(url, {
- headers: {
- Authorization: `Bearer ${auth.session}`,
- },
- });
- const data = await response.json();
-
- return data.response;
- },
- initialPageParam: 0,
- refetchOnWindowFocus: false,
- getNextPageParam: (lastPage) => {
- if (lastPage.length === 0) {
- return undefined;
- }
- return lastPage.at(-1).id;
- },
- enabled: !!auth.session,
- });
-};
-
-const buildQueryString = (params: LinkRequestQuery) => {
- return Object.keys(params)
- .filter((key) => params[key as keyof LinkRequestQuery] !== undefined)
- .map(
- (key) =>
- `${encodeURIComponent(key)}=${encodeURIComponent(
- params[key as keyof LinkRequestQuery] as string
- )}`
- )
- .join("&");
-};
-
-const useAddLink = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async (link: any) => {
- if (link.url || link.type === "url") {
- try {
- new URL(link.url || "");
- } catch (error) {
- throw new Error("invalid_url_guide");
- }
- }
-
- const response = await fetch("/api/v1/links", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(link),
- });
-
- const data = await response.json();
-
- if (!response.ok) throw new Error(data.response);
-
- return data.response;
- },
- onSuccess: (data) => {
- queryClient.setQueryData(["dashboardData"], (oldData: any) => {
- if (!oldData?.links) return undefined;
- return {
- ...oldData,
- links: [data, ...oldData?.links],
- };
- });
-
- queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
- if (!oldData) return undefined;
- return {
- pages: [[data, ...oldData?.pages[0]], ...oldData?.pages.slice(1)],
- pageParams: oldData?.pageParams,
- };
- });
-
- queryClient.invalidateQueries({ queryKey: ["collections"] });
- queryClient.invalidateQueries({ queryKey: ["tags"] });
- queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
- },
- });
-};
-
-const useUpdateLink = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async (link: LinkIncludingShortenedCollectionAndTags) => {
- const response = await fetch(`/api/v1/links/${link.id}`, {
- method: "PUT",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(link),
- });
-
- const data = await response.json();
-
- if (!response.ok) throw new Error(data.response);
-
- return data.response;
- },
- onSuccess: (data) => {
- // queryClient.setQueryData(["dashboardData"], (oldData: any) => {
- // if (!oldData?.links) return undefined;
- // return oldData.links.map((e: any) => (e.id === data.id ? data : e));
- // });
-
- // queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
- // if (!oldData) return undefined;
- // return {
- // pages: oldData.pages.map((page: any) =>
- // page.map((item: any) => (item.id === data.id ? data : item))
- // ),
- // pageParams: oldData.pageParams,
- // };
- // });
-
- queryClient.invalidateQueries({ queryKey: ["links"] }); // Temporary workaround
- queryClient.invalidateQueries({ queryKey: ["dashboardData"] }); // Temporary workaround
-
- queryClient.invalidateQueries({ queryKey: ["collections"] });
- queryClient.invalidateQueries({ queryKey: ["tags"] });
- queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
- },
- });
-};
-
-const useDeleteLink = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async (id: number) => {
- const response = await fetch(`/api/v1/links/${id}`, {
- method: "DELETE",
- });
-
- const data = await response.json();
-
- if (!response.ok) throw new Error(data.response);
-
- return data.response;
- },
- onSuccess: (data) => {
- queryClient.setQueryData(["dashboardData"], (oldData: any) => {
- if (!oldData?.links) return undefined;
- return {
- ...oldData,
- links: oldData.links.filter((e: any) => e.id !== data.id),
- };
- });
-
- queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
- if (!oldData) return undefined;
- return {
- pages: oldData.pages.map((page: any) =>
- page.filter((item: any) => item.id !== data.id)
- ),
- pageParams: oldData.pageParams,
- };
- });
-
- queryClient.invalidateQueries({ queryKey: ["collections"] });
- queryClient.invalidateQueries({ queryKey: ["tags"] });
- queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
- },
- });
-};
-
-const useGetLink = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async ({ id }: { id: number }) => {
- const path = `/api/v1/links/${id}`;
-
- const response = await fetch(path);
- const data = await response.json();
-
- if (!response.ok) throw new Error(data.response);
-
- return data.response;
- },
- onSuccess: (data) => {
- queryClient.setQueryData(["dashboardData"], (oldData: any) => {
- if (!oldData?.links) return undefined;
- return {
- ...oldData,
- links: oldData.links.map((e: any) => (e.id === data.id ? data : e)),
- };
- });
-
- queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
- if (!oldData) return undefined;
- return {
- pages: oldData.pages.map((page: any) =>
- page.map((item: any) => (item.id === data.id ? data : item))
- ),
- pageParams: oldData.pageParams,
- };
- });
-
- queryClient.setQueriesData(
- { queryKey: ["publicLinks"] },
- (oldData: any) => {
- if (!oldData) return undefined;
- return {
- pages: oldData.pages.map((page: any) =>
- page.map((item: any) => (item.id === data.id ? data : item))
- ),
- pageParams: oldData.pageParams,
- };
- }
- );
-
- // queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
- },
- });
-};
-
-const useBulkDeleteLinks = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async (linkIds: number[]) => {
- const response = await fetch("/api/v1/links", {
- method: "DELETE",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ linkIds }),
- });
-
- const data = await response.json();
-
- if (!response.ok) throw new Error(data.response);
-
- return linkIds;
- },
- onSuccess: (data) => {
- queryClient.setQueryData(["dashboardData"], (oldData: any) => {
- if (!oldData?.links) return undefined;
- return oldData.links.filter((e: any) => !data.includes(e.id));
- });
-
- queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
- if (!oldData) return undefined;
- return {
- pages: oldData.pages.map((page: any) =>
- page.filter((item: any) => !data.includes(item.id))
- ),
- pageParams: oldData.pageParams,
- };
- });
-
- queryClient.invalidateQueries({ queryKey: ["collections"] });
- queryClient.invalidateQueries({ queryKey: ["tags"] });
- queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
- },
- });
-};
-
-const useUploadFile = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async ({ link, file }: any) => {
- let fileType: ArchivedFormat | null = null;
- let linkType: "url" | "image" | "pdf" | null = null;
-
- if (file?.type === "image/jpg" || file.type === "image/jpeg") {
- fileType = ArchivedFormat.jpeg;
- linkType = "image";
- } else if (file.type === "image/png") {
- fileType = ArchivedFormat.png;
- linkType = "image";
- } else if (file.type === "application/pdf") {
- fileType = ArchivedFormat.pdf;
- linkType = "pdf";
- } else {
- return { ok: false, data: "Invalid file type." };
- }
-
- const response = await fetch("/api/v1/links", {
- body: JSON.stringify({
- ...link,
- type: linkType,
- name: link.name ? link.name : file.name,
- }),
- headers: {
- "Content-Type": "application/json",
- },
- method: "POST",
- });
-
- const data = await response.json();
-
- if (!response.ok) throw new Error(data.response);
-
- if (response.ok) {
- const formBody = new FormData();
- file && formBody.append("file", file);
-
- await fetch(
- `/api/v1/archives/${(data as any).response.id}?format=${fileType}`,
- {
- body: formBody,
- method: "POST",
- }
- );
- }
-
- return data.response;
- },
- onSuccess: (data) => {
- queryClient.setQueryData(["dashboardData"], (oldData: any) => {
- if (!oldData?.links) return undefined;
- return {
- ...oldData,
- links: [data, ...oldData?.links],
- };
- });
-
- queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
- if (!oldData) return undefined;
- return {
- pages: [[data, ...oldData?.pages[0]], ...oldData?.pages.slice(1)],
- pageParams: oldData?.pageParams,
- };
- });
-
- queryClient.invalidateQueries({ queryKey: ["collections"] });
- queryClient.invalidateQueries({ queryKey: ["tags"] });
- queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
- },
- });
-};
-
-const useUpdatePreview = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async ({ linkId, file }: { linkId: number; file: File }) => {
- const formBody = new FormData();
-
- if (!linkId || !file)
- throw new Error("Error generating preview: Invalid parameters");
-
- formBody.append("file", file);
-
- const res = await fetch(
- `/api/v1/archives/${linkId}?format=` + ArchivedFormat.jpeg,
- {
- body: formBody,
- method: "PUT",
- }
- );
-
- const data = res.json();
-
- return data;
- },
- onSuccess: (data) => {
- queryClient.setQueryData(["dashboardData"], (oldData: any) => {
- if (!oldData?.links) return undefined;
- return {
- ...oldData,
- links: oldData.links.map((e: any) =>
- e.id === data.response.id
- ? {
- ...e,
- preview: `archives/preview/${e.collectionId}/${e.id}.jpeg`,
- }
- : e
- ),
- };
- });
-
- queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
- if (!oldData) return undefined;
- return {
- pages: oldData.pages.map((page: any) =>
- page.map((item: any) =>
- item.id === data.response.id
- ? {
- ...item,
- preview: `archives/preview/${item.collectionId}/${item.id}.jpeg`,
- updatedAt: new Date().toISOString(),
- }
- : item
- )
- ),
- pageParams: oldData.pageParams,
- };
- });
- },
- });
-};
-
-const useBulkEditLinks = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async ({
- links,
- newData,
- removePreviousTags,
- }: {
- links: LinkIncludingShortenedCollectionAndTags[];
- newData: Pick<
- LinkIncludingShortenedCollectionAndTags,
- "tags" | "collectionId"
- >;
- removePreviousTags: boolean;
- }) => {
- const response = await fetch("/api/v1/links", {
- method: "PUT",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ links, newData, removePreviousTags }),
- });
-
- const data = await response.json();
-
- if (!response.ok) throw new Error(data.response);
-
- return data.response;
- },
- onSuccess: (data, { links, newData, removePreviousTags }) => {
- // TODO: Fix these
- // queryClient.setQueryData(["dashboardData"], (oldData: any) => {
- // if (!oldData?.links) return undefined;
- // return oldData.links.map((e: any) =>
- // data.find((d: any) => d.id === e.id) ? data : e
- // );
- // });
- // queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
- // if (!oldData) return undefined;
- // return {
- // pages: oldData.pages.map((page: any) => for (item of links) {
- // page.map((item: any) => (item.id === data.id ? data : item))
- // }
- // ),
- // pageParams: oldData.pageParams,
- // };
- // });
- queryClient.invalidateQueries({ queryKey: ["links"] }); // Temporary workaround
- queryClient.invalidateQueries({ queryKey: ["dashboardData"] }); // Temporary workaround
-
- queryClient.invalidateQueries({ queryKey: ["collections"] });
- queryClient.invalidateQueries({ queryKey: ["tags"] });
- queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
- },
- });
-};
-
-const resetInfiniteQueryPagination = async (
- queryClient: any,
- queryKey: any
-) => {
- queryClient.setQueriesData({ queryKey }, (oldData: any) => {
- if (!oldData) return undefined;
-
- return {
- pages: oldData.pages.slice(0, 1),
- pageParams: oldData.pageParams.slice(0, 1),
- };
- });
-
- await queryClient.invalidateQueries(queryKey);
-};
-
-export {
- useLinks,
- useAddLink,
- useUpdateLink,
- useDeleteLink,
- useBulkDeleteLinks,
- useUploadFile,
- useGetLink,
- useBulkEditLinks,
- resetInfiniteQueryPagination,
- useUpdatePreview,
-};
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index 2d9785e8..21d45404 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -15,11 +15,13 @@
"preset": "jest-expo"
},
"dependencies": {
+ "@linkwarden/router": "*",
+ "@linkwarden/lib": "*",
"@expo/vector-icons": "^14.0.2",
"@react-native-menu/menu": "1.2.2",
"@react-navigation/bottom-tabs": "^7.0.0",
"@react-navigation/native": "^7.0.0",
- "@tanstack/react-query": "^5.62.7",
+ "@tanstack/react-query": "^5.51.15",
"expo": "~52.0.18",
"expo-blur": "~14.0.1",
"expo-constants": "~17.0.3",
diff --git a/apps/mobile/store/auth.ts b/apps/mobile/store/auth.ts
index 25501e24..0b756aa6 100644
--- a/apps/mobile/store/auth.ts
+++ b/apps/mobile/store/auth.ts
@@ -3,7 +3,7 @@ import * as SecureStore from "expo-secure-store";
import { router } from "expo-router";
type Auth = {
- state: "loading" | "authenticated" | "unauthenticated";
+ status: "loading" | "authenticated" | "unauthenticated";
session: string | null;
instance: string | null;
};
@@ -19,7 +19,7 @@ const useAuthStore = create<AuthStore>((set) => ({
auth: {
instance: "",
session: null,
- state: "loading",
+ status: "loading",
},
setAuth: async () => {
const session = await SecureStore.getItemAsync("TOKEN");
@@ -30,7 +30,7 @@ const useAuthStore = create<AuthStore>((set) => ({
auth: {
instance,
session,
- state: "authenticated",
+ status: "authenticated",
},
});
} else {
@@ -38,7 +38,7 @@ const useAuthStore = create<AuthStore>((set) => ({
auth: {
instance: "",
session: null,
- state: "unauthenticated",
+ status: "unauthenticated",
},
});
}
@@ -69,7 +69,7 @@ const useAuthStore = create<AuthStore>((set) => ({
auth: {
session,
instance,
- state: "authenticated",
+ status: "authenticated",
},
});
@@ -79,7 +79,7 @@ const useAuthStore = create<AuthStore>((set) => ({
auth: {
instance,
session: null,
- state: "unauthenticated",
+ status: "unauthenticated",
},
});
}
@@ -91,7 +91,7 @@ const useAuthStore = create<AuthStore>((set) => ({
auth: {
instance: "",
session: null,
- state: "unauthenticated",
+ status: "unauthenticated",
},
});
diff --git a/apps/mobile/tsconfig.json b/apps/mobile/tsconfig.json
index 909e9010..ce27fee3 100644
--- a/apps/mobile/tsconfig.json
+++ b/apps/mobile/tsconfig.json
@@ -3,15 +3,8 @@
"compilerOptions": {
"strict": true,
"paths": {
- "@/*": [
- "./*"
- ]
+ "@/*": ["./*"]
}
},
- "include": [
- "**/*.ts",
- "**/*.tsx",
- ".expo/types/**/*.ts",
- "expo-env.d.ts"
- ]
+ "include": ["**/*.ts", "**/*.tsx", ".expo/types/**/*.ts", "expo-env.d.ts"]
}
diff --git a/apps/web/components/LinkDetails.tsx b/apps/web/components/LinkDetails.tsx
index a072e229..84a85e48 100644
--- a/apps/web/components/LinkDetails.tsx
+++ b/apps/web/components/LinkDetails.tsx
@@ -61,8 +61,12 @@ export default function LinkDetails({
const permissions = usePermissions(link.collection.id as number);
const { t } = useTranslation();
- const getLink = useGetLink();
const { data: user = {} } = useUser();
+ const router = useRouter();
+
+ const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
+
+ const getLink = useGetLink(isPublicRoute);
const [collectionOwner, setCollectionOwner] = useState({
id: null as unknown as number,
@@ -135,10 +139,6 @@ export default function LinkDetails({
};
}, [link.monolith]);
- const router = useRouter();
-
- const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
-
const updateLink = useUpdateLink();
const updateFile = useUpdateFile();
diff --git a/apps/web/components/LinkViews/LinkComponents/LinkActions.tsx b/apps/web/components/LinkViews/LinkComponents/LinkActions.tsx
index 253c4dfa..05d29ad0 100644
--- a/apps/web/components/LinkViews/LinkComponents/LinkActions.tsx
+++ b/apps/web/components/LinkViews/LinkComponents/LinkActions.tsx
@@ -31,6 +31,11 @@ export default function LinkActions({
const { t } = useTranslation();
const permissions = usePermissions(link.collection.id as number);
+
+ const router = useRouter();
+
+ const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
+
const getLink = useGetLink();
const pinLink = usePinLink();
@@ -57,10 +62,6 @@ export default function LinkActions({
} else toast.error(data.response);
};
- const router = useRouter();
-
- const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
-
return (
<>
{isPublicRoute ? (
diff --git a/apps/web/components/LinkViews/LinkComponents/LinkCard.tsx b/apps/web/components/LinkViews/LinkComponents/LinkCard.tsx
index 9ae5a150..f6384dd3 100644
--- a/apps/web/components/LinkViews/LinkComponents/LinkCard.tsx
+++ b/apps/web/components/LinkViews/LinkComponents/LinkCard.tsx
@@ -67,6 +67,10 @@ export default function LinkCard({ link, columns, editMode }: Props) {
} = useLocalSettingsStore();
const { links } = useLinks();
+
+ const router = useRouter();
+ const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
+
const getLink = useGetLink();
useEffect(() => {
@@ -114,9 +118,6 @@ export default function LinkCard({ link, columns, editMode }: Props) {
const isVisible = useOnScreen(ref);
const permissions = usePermissions(collection?.id as number);
- const router = useRouter();
- const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
-
const [linkModal, setLinkModal] = useState(false);
useEffect(() => {
diff --git a/apps/web/components/LinkViews/LinkComponents/LinkMasonry.tsx b/apps/web/components/LinkViews/LinkComponents/LinkMasonry.tsx
index 6eebd481..de6aad80 100644
--- a/apps/web/components/LinkViews/LinkComponents/LinkMasonry.tsx
+++ b/apps/web/components/LinkViews/LinkComponents/LinkMasonry.tsx
@@ -66,6 +66,11 @@ export default function LinkMasonry({ link, editMode, columns }: Props) {
} = useLocalSettingsStore();
const { links } = useLinks();
+
+ const router = useRouter();
+
+ let isPublic = router.pathname.startsWith("/public") ? true : undefined;
+
const getLink = useGetLink();
useEffect(() => {
@@ -113,10 +118,6 @@ export default function LinkMasonry({ link, editMode, columns }: Props) {
const isVisible = useOnScreen(ref);
const permissions = usePermissions(collection?.id as number);
- const router = useRouter();
-
- let isPublic = router.pathname.startsWith("/public") ? true : undefined;
-
useEffect(() => {
let interval: NodeJS.Timeout | null = null;
diff --git a/apps/web/components/Preservation/PreservationPageContent.tsx b/apps/web/components/Preservation/PreservationPageContent.tsx
index 3a281d12..77ed048a 100644
--- a/apps/web/components/Preservation/PreservationPageContent.tsx
+++ b/apps/web/components/Preservation/PreservationPageContent.tsx
@@ -5,9 +5,14 @@ import { PreservationContent } from "./PreservationContent";
export default function PreservationPageContent() {
const router = useRouter();
- const isPublicRoute = router.pathname.startsWith("/public");
- const { data: link, mutateAsync: fetchLink, error } = useGetLink();
+ let isPublicRoute = router.pathname.startsWith("/public") ? true : undefined;
+
+ const {
+ data: link,
+ mutateAsync: fetchLink,
+ error,
+ } = useGetLink(isPublicRoute);
useEffect(() => {
fetchLink({
diff --git a/apps/web/pages/links/[id].tsx b/apps/web/pages/links/[id].tsx
index 7b054109..ce6cc98b 100644
--- a/apps/web/pages/links/[id].tsx
+++ b/apps/web/pages/links/[id].tsx
@@ -1,16 +1,16 @@
import LinkDetails from "@/components/LinkDetails";
import { useGetLink } from "@linkwarden/router/links";
import { useRouter } from "next/router";
-import { useEffect, useState } from "react";
+import { useEffect } from "react";
import getServerSideProps from "@/lib/client/getServerSideProps";
const Index = () => {
const router = useRouter();
const { id } = router.query;
- useState;
+ let isPublicRoute = router.pathname.startsWith("/public") ? true : undefined;
- const getLink = useGetLink();
+ const getLink = useGetLink(isPublicRoute);
useEffect(() => {
getLink.mutate({ id: Number(id) });
diff --git a/apps/web/pages/public/links/[id].tsx b/apps/web/pages/public/links/[id].tsx
index 4c764ede..ce6cc98b 100644
--- a/apps/web/pages/public/links/[id].tsx
+++ b/apps/web/pages/public/links/[id].tsx
@@ -8,7 +8,9 @@ const Index = () => {
const router = useRouter();
const { id } = router.query;
- const getLink = useGetLink();
+ let isPublicRoute = router.pathname.startsWith("/public") ? true : undefined;
+
+ const getLink = useGetLink(isPublicRoute);
useEffect(() => {
getLink.mutate({ id: Number(id) });
diff --git a/packages/router/links.tsx b/packages/router/links.tsx
index 46f6da23..8a7fe247 100644
--- a/packages/router/links.tsx
+++ b/packages/router/links.tsx
@@ -9,32 +9,30 @@ import {
LinkIncludingShortenedCollectionAndTags,
LinkRequestQuery,
} from "@linkwarden/types";
-import { useRouter } from "next/router";
import { useSession } from "next-auth/react";
import { PostLinkSchemaType } from "@linkwarden/lib/schemaValidation";
import getFormatFromContentType from "@linkwarden/lib/getFormatFromContentType";
import getLinkTypeFromFormat from "@linkwarden/lib/getLinkTypeFromFormat";
-const useLinks = (params: LinkRequestQuery = {}) => {
- const router = useRouter();
-
+const useLinks = (
+ params: LinkRequestQuery = {},
+ auth?: {
+ status: "loading" | "authenticated" | "unauthenticated";
+ session: string | null;
+ instance: string | null;
+ }
+) => {
const queryParamsObject = {
sort: params.sort ?? Number(window.localStorage.getItem("sortBy")) ?? 0,
- collectionId:
- params.collectionId ??
- (router.pathname === "/collections/[id]" ? router.query.id : undefined),
- tagId:
- params.tagId ??
- (router.pathname === "/tags/[id]" ? router.query.id : undefined),
- pinnedOnly:
- params.pinnedOnly ??
- (router.pathname === "/links/pinned" ? true : undefined),
+ collectionId: params.collectionId,
+ tagId: params.tagId,
+ pinnedOnly: params.pinnedOnly ?? undefined,
searchQueryString: params.searchQueryString,
} as LinkRequestQuery;
const queryString = buildQueryString(queryParamsObject);
- const { data, ...rest } = useFetchLinks(queryString);
+ const { data, ...rest } = useFetchLinks(queryString, auth);
const links = useMemo(() => {
return data?.pages?.flatMap((page) => page?.links ?? []) ?? [];
@@ -48,18 +46,40 @@ const useLinks = (params: LinkRequestQuery = {}) => {
};
};
-const useFetchLinks = (params: string) => {
- const { status } = useSession();
+const useFetchLinks = (
+ params: string,
+ auth?: {
+ status: "loading" | "authenticated" | "unauthenticated";
+ session: string | null;
+ instance: string | null;
+ }
+) => {
+ let status: "loading" | "authenticated" | "unauthenticated";
+
+ if (!auth) {
+ const session = useSession();
+ status = session.status;
+ } else {
+ status = auth?.status;
+ }
return useInfiniteQuery({
queryKey: ["links", { params }],
queryFn: async (params) => {
const response = await fetch(
- "/api/v1/search?cursor=" +
+ auth?.instance +
+ "/api/v1/search?cursor=" +
params.pageParam +
((params.queryKey[1] as any).params
? "&" + (params.queryKey[1] as any).params
- : "")
+ : ""),
+ auth?.session
+ ? {
+ headers: {
+ Authorization: `Bearer ${auth.session}`,
+ },
+ }
+ : undefined
);
const data = await response.json();
@@ -221,19 +241,11 @@ const useDeleteLink = () => {
});
};
-const useGetLink = () => {
+const useGetLink = (isPublicRoute?: boolean) => {
const queryClient = useQueryClient();
- const router = useRouter();
-
return useMutation({
- mutationFn: async ({
- id,
- isPublicRoute = router.pathname.startsWith("/public") ? true : undefined,
- }: {
- id: number;
- isPublicRoute?: boolean;
- }) => {
+ mutationFn: async ({ id }: { id: number }) => {
const path = isPublicRoute
? `/api/v1/public/links/${id}`
: `/api/v1/links/${id}`;
diff --git a/yarn.lock b/yarn.lock
index 1bf0a7bf..0cf77b44 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4175,11 +4175,6 @@
resolved "https://registry.yarnpkg.com/@tanstack/query-core/-/query-core-5.51.15.tgz#7aee6a2d5d3f64de3e54096607233b1132dc6afd"
integrity sha512-xyobHDJ0yhPE3+UkSQ2/4X1fLSg7ICJI5J1JyU9yf7F3deQfEwSImCDrB1WSRrauJkMtXW7YIEcC0oA6ZZWt5A==
-"@tanstack/[email protected]":
- version "5.74.4"
- resolved "https://registry.yarnpkg.com/@tanstack/query-core/-/query-core-5.74.4.tgz#08c4f88f336738d822d9242c5e7d2be50f5c25b3"
- integrity sha512-YuG0A0+3i9b2Gfo9fkmNnkUWh5+5cFhWBN0pJAHkHilTx6A0nv8kepkk4T4GRt4e5ahbtFj2eTtkiPcVU1xO4A==
-
"@tanstack/[email protected]":
version "5.51.15"
resolved "https://registry.yarnpkg.com/@tanstack/query-devtools/-/query-devtools-5.51.15.tgz#81c5c28231adc4b95fe4a5e1004020fdca5ea447"
@@ -4199,13 +4194,6 @@
dependencies:
"@tanstack/query-core" "5.51.15"
-"@tanstack/react-query@^5.62.7":
- version "5.74.4"
- resolved "https://registry.yarnpkg.com/@tanstack/react-query/-/react-query-5.74.4.tgz#d73ee1899c08a227519cbf53b9a0e0b1e67cd3fe"
- integrity sha512-mAbxw60d4ffQ4qmRYfkO1xzRBPUEf/72Dgo3qqea0J66nIKuDTLEqQt0ku++SDFlMGMnB6uKDnEG1xD/TDse4Q==
- dependencies:
- "@tanstack/query-core" "5.74.4"
-
"@tokenizer/token@^0.3.0":
version "0.3.0"
resolved "https://registry.yarnpkg.com/@tokenizer/token/-/token-0.3.0.tgz#fe98a93fe789247e998c75e74e9c7c63217aa276"