feat: add error messages to user pages

This commit is contained in:
Kentai Radiquum 2025-03-20 22:02:49 +05:00
parent f2f03df1a0
commit d16e4d14d4
Signed by: Radiquum
GPG key ID: 858E8EE696525EED
10 changed files with 285 additions and 136 deletions

View file

@ -4,6 +4,84 @@ export const HEADERS = {
"Content-Type": "application/json; charset=UTF-8",
};
// Types for the result object with discriminated union
type Success<T> = {
data: T;
error: null;
};
type Failure<E> = {
data: null;
error: E;
};
type Result<T, E = Error> = Success<T> | Failure<E>;
// Main wrapper function
export async function tryCatch<T, E = Error>(
promise: Promise<T>
): Promise<Result<T, E>> {
try {
const data = await promise;
return { data, error: null };
} catch (error) {
return { data: null, error: error as E };
}
}
export async function tryCatchAPI<T, E = Error>(
promise: Promise<any>
): Promise<Result<any, E>> {
try {
const res: Awaited<Response> = await promise;
if (!res.ok) {
return {
data: null,
error: JSON.stringify({
message: res.statusText,
code: res.status,
}) as E,
};
}
if (
res.headers.get("content-length") &&
Number(res.headers.get("content-length")) == 0
) {
return {
data: null,
error: {
message: "Not Found",
code: 404,
} as E,
};
}
const data: Awaited<any> = await res.json();
if (data.code != 0) {
return {
data: null,
error: {
message: "API Returned an Error",
code: data.code || 500,
} as E,
};
}
return { data, error: null };
} catch (error) {
return { data: null, error: error as E };
}
}
export const useSWRfetcher = async (url: string) => {
const { data, error } = await tryCatchAPI(fetch(url));
if (error) {
throw error;
}
return data;
};
export const fetchDataViaGet = async (
url: string,
API_V2: string | boolean = false
@ -11,18 +89,14 @@ export const fetchDataViaGet = async (
if (API_V2) {
HEADERS["API-Version"] = "v2";
}
try {
const response = await fetch(url, {
const { data, error } = await tryCatchAPI(
fetch(url, {
headers: HEADERS,
});
if (response.status !== 200) {
return null;
}
const data = await response.json();
return data;
} catch (error) {
console.log(error);
}
})
);
return { data, error };
};
export const fetchDataViaPost = async (

View file

@ -2,11 +2,9 @@
import useSWR from "swr";
import { ReleaseCourusel } from "#/components/ReleaseCourusel/ReleaseCourusel";
import { Spinner } from "#/components/Spinner/Spinner";
const fetcher = (...args: any) =>
fetch([...args] as any).then((res) => res.json());
import { useUserStore } from "#/store/auth";
import { usePreferencesStore } from "#/store/preferences";
import { BookmarksList } from "#/api/utils";
import { BookmarksList, useSWRfetcher } from "#/api/utils";
import { ENDPOINTS } from "#/api/config";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
@ -35,7 +33,7 @@ export function BookmarksPage(props: { profile_id?: number }) {
function useFetchReleases(listName: string) {
let url: string;
if (preferenceStore.params.skipToCategory.enabled) {
return [null];
return [null, null];
}
if (props.profile_id) {
@ -50,8 +48,9 @@ export function BookmarksPage(props: { profile_id?: number }) {
}
// eslint-disable-next-line react-hooks/rules-of-hooks
const { data } = useSWR(url, fetcher);
return [data];
const { data, error } = useSWR(url, useSWRfetcher);
console.log(data, error);
return [data, error];
}
useEffect(() => {
@ -61,11 +60,11 @@ export function BookmarksPage(props: { profile_id?: number }) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [authState, token]);
const [watchingData] = useFetchReleases("watching");
const [plannedData] = useFetchReleases("planned");
const [watchedData] = useFetchReleases("watched");
const [delayedData] = useFetchReleases("delayed");
const [abandonedData] = useFetchReleases("abandoned");
const [watchingData, watchingError] = useFetchReleases("watching");
const [plannedData, plannedError] = useFetchReleases("planned");
const [watchedData, watchedError] = useFetchReleases("watched");
const [delayedData, delayedError] = useFetchReleases("delayed");
const [abandonedData, abandonedError] = useFetchReleases("abandoned");
return (
<>
@ -85,8 +84,8 @@ export function BookmarksPage(props: { profile_id?: number }) {
<ReleaseCourusel
sectionTitle="Смотрю"
showAllLink={
!props.profile_id
? "/bookmarks/watching"
!props.profile_id ?
"/bookmarks/watching"
: `/profile/${props.profile_id}/bookmarks/watching`
}
content={watchingData.content}
@ -96,9 +95,9 @@ export function BookmarksPage(props: { profile_id?: number }) {
<ReleaseCourusel
sectionTitle="В планах"
showAllLink={
!props.profile_id
? "/bookmarks/planned"
: `/profile/${props.profile_id}/bookmarks/planned`
!props.profile_id ? "/bookmarks/planned" : (
`/profile/${props.profile_id}/bookmarks/planned`
)
}
content={plannedData.content}
/>
@ -107,9 +106,9 @@ export function BookmarksPage(props: { profile_id?: number }) {
<ReleaseCourusel
sectionTitle="Просмотрено"
showAllLink={
!props.profile_id
? "/bookmarks/watched"
: `/profile/${props.profile_id}/bookmarks/watched`
!props.profile_id ? "/bookmarks/watched" : (
`/profile/${props.profile_id}/bookmarks/watched`
)
}
content={watchedData.content}
/>
@ -118,9 +117,9 @@ export function BookmarksPage(props: { profile_id?: number }) {
<ReleaseCourusel
sectionTitle="Отложено"
showAllLink={
!props.profile_id
? "/bookmarks/delayed"
: `/profile/${props.profile_id}/bookmarks/delayed`
!props.profile_id ? "/bookmarks/delayed" : (
`/profile/${props.profile_id}/bookmarks/delayed`
)
}
content={delayedData.content}
/>
@ -131,13 +130,28 @@ export function BookmarksPage(props: { profile_id?: number }) {
<ReleaseCourusel
sectionTitle="Заброшено"
showAllLink={
!props.profile_id
? "/bookmarks/abandoned"
!props.profile_id ?
"/bookmarks/abandoned"
: `/profile/${props.profile_id}/bookmarks/abandoned`
}
content={abandonedData.content}
/>
)}
{(watchingError ||
plannedError ||
watchedError ||
delayedError ||
abandonedError) && (
<main className="flex items-center justify-center min-h-screen">
<div className="flex flex-col gap-2">
<h1 className="text-2xl font-bold">Ошибка</h1>
<p className="text-lg">
Произошла ошибка при загрузке закладок. Попробуйте обновить
страницу или зайдите позже.
</p>
</div>
</main>
)}
</>
);
}

View file

@ -5,10 +5,10 @@ import { Spinner } from "#/components/Spinner/Spinner";
import { useState, useEffect } from "react";
import { useScrollPosition } from "#/hooks/useScrollPosition";
import { useUserStore } from "../store/auth";
import { Dropdown, Button, Tabs } from "flowbite-react";
import { Dropdown, Button } from "flowbite-react";
import { sort } from "./common";
import { ENDPOINTS } from "#/api/config";
import { BookmarksList } from "#/api/utils";
import { BookmarksList, useSWRfetcher } from "#/api/utils";
import { useRouter } from "next/navigation";
const DropdownTheme = {
@ -17,25 +17,10 @@ const DropdownTheme = {
},
};
const fetcher = async (url: string) => {
const res = await fetch(url);
if (!res.ok) {
const error = new Error(
`An error occurred while fetching the data. status: ${res.status}`
);
error.message = await res.json();
throw error;
}
return res.json();
};
export function BookmarksCategoryPage(props: any) {
const token = useUserStore((state) => state.token);
const authState = useUserStore((state) => state.state);
const [selectedSort, setSelectedSort] = useState(0);
const [isLoadingEnd, setIsLoadingEnd] = useState(false);
const [searchVal, setSearchVal] = useState("");
const router = useRouter();
@ -61,7 +46,7 @@ export function BookmarksCategoryPage(props: any) {
const { data, error, isLoading, size, setSize } = useSWRInfinite(
getKey,
fetcher,
useSWRfetcher,
{ initialSize: 2 }
);
@ -73,7 +58,6 @@ export function BookmarksCategoryPage(props: any) {
allReleases.push(...data[i].content);
}
setContent(allReleases);
setIsLoadingEnd(true);
}
}, [data]);
@ -92,9 +76,31 @@ export function BookmarksCategoryPage(props: any) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [authState, token]);
if (isLoading) {
return (
<div className="flex flex-col items-center justify-center min-w-full min-h-screen">
<Spinner />
</div>
);
};
if (error) {
return (
<main className="flex items-center justify-center min-h-screen">
<div className="flex flex-col gap-2">
<h1 className="text-2xl font-bold">Ошибка</h1>
<p className="text-lg">
Произошла ошибка при загрузке закладок. Попробуйте обновить страницу
или зайдите позже.
</p>
</div>
</main>
);
}
return (
<>
{!props.profile_id ? (
{!props.profile_id ?
<form
className="flex-1 max-w-full mx-4"
onSubmit={(e) => {
@ -143,9 +149,7 @@ export function BookmarksCategoryPage(props: any) {
</button>
</div>
</form>
) : (
""
)}
: ""}
<div className="m-4 overflow-auto">
<Button.Group>
<Button
@ -154,8 +158,8 @@ export function BookmarksCategoryPage(props: any) {
color="light"
onClick={() =>
router.push(
props.profile_id
? `/profile/${props.profile_id}/bookmarks/watching`
props.profile_id ?
`/profile/${props.profile_id}/bookmarks/watching`
: "/bookmarks/watching"
)
}
@ -168,8 +172,8 @@ export function BookmarksCategoryPage(props: any) {
color="light"
onClick={() =>
router.push(
props.profile_id
? `/profile/${props.profile_id}/bookmarks/planned`
props.profile_id ?
`/profile/${props.profile_id}/bookmarks/planned`
: "/bookmarks/planned"
)
}
@ -182,8 +186,8 @@ export function BookmarksCategoryPage(props: any) {
color="light"
onClick={() =>
router.push(
props.profile_id
? `/profile/${props.profile_id}/bookmarks/watched`
props.profile_id ?
`/profile/${props.profile_id}/bookmarks/watched`
: "/bookmarks/watched"
)
}
@ -196,8 +200,8 @@ export function BookmarksCategoryPage(props: any) {
color="light"
onClick={() =>
router.push(
props.profile_id
? `/profile/${props.profile_id}/bookmarks/delayed`
props.profile_id ?
`/profile/${props.profile_id}/bookmarks/delayed`
: "/bookmarks/delayed"
)
}
@ -210,8 +214,8 @@ export function BookmarksCategoryPage(props: any) {
color="light"
onClick={() =>
router.push(
props.profile_id
? `/profile/${props.profile_id}/bookmarks/abandoned`
props.profile_id ?
`/profile/${props.profile_id}/bookmarks/abandoned`
: "/bookmarks/abandoned"
)
}
@ -236,8 +240,8 @@ export function BookmarksCategoryPage(props: any) {
<Dropdown.Item key={index} onClick={() => setSelectedSort(index)}>
<span
className={`w-6 h-6 iconify ${
sort.values[index].value.split("_")[1] == "descending"
? sort.descendingIcon
sort.values[index].value.split("_")[1] == "descending" ?
sort.descendingIcon
: sort.ascendingIcon
}`}
></span>
@ -246,20 +250,15 @@ export function BookmarksCategoryPage(props: any) {
))}
</Dropdown>
</div>
{content && content.length > 0 ? (
{content && content.length > 0 ?
<ReleaseSection content={content} />
) : !isLoadingEnd || isLoading ? (
<div className="flex flex-col items-center justify-center min-w-full min-h-screen">
<Spinner />
</div>
) : (
<div className="flex flex-col items-center justify-center min-w-full gap-4 mt-12 text-xl">
: <div className="flex flex-col items-center justify-center min-w-full gap-4 mt-12 text-xl">
<span className="w-24 h-24 iconify-color twemoji--broken-heart"></span>
<p>
В списке {props.SectionTitleMapping[props.slug]} пока ничего нет...
</p>
</div>
)}
}
{data &&
data[data.length - 1].current_page <
data[data.length - 1].total_page_count && (

View file

@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
import { Spinner } from "../components/Spinner/Spinner";
import { ENDPOINTS } from "#/api/config";
import useSWR from "swr";
import { useSWRfetcher } from "#/api/utils";
import { ProfileUser } from "#/components/Profile/Profile.User";
import { ProfileBannedBanner } from "#/components/Profile/ProfileBannedBanner";
@ -16,20 +17,6 @@ import { ProfileReleaseRatings } from "#/components/Profile/Profile.ReleaseRatin
import { ProfileReleaseHistory } from "#/components/Profile/Profile.ReleaseHistory";
import { ProfileEditModal } from "#/components/Profile/Profile.EditModal";
const fetcher = async (url: string) => {
const res = await fetch(url);
if (!res.ok) {
const error = new Error(
`An error occurred while fetching the data. status: ${res.status}`
);
error.message = await res.json();
throw error;
}
return res.json();
};
export const ProfilePage = (props: any) => {
const authUser = useUserStore();
const [user, setUser] = useState(null);
@ -41,7 +28,7 @@ export const ProfilePage = (props: any) => {
if (authUser.token) {
url += `?token=${authUser.token}`;
}
const { data } = useSWR(url, fetcher);
const { data, error } = useSWR(url, useSWRfetcher);
useEffect(() => {
if (data) {
@ -50,7 +37,7 @@ export const ProfilePage = (props: any) => {
}
}, [data]);
if (!user) {
if (!user && !error) {
return (
<main className="flex items-center justify-center min-h-screen">
<Spinner />
@ -58,6 +45,20 @@ export const ProfilePage = (props: any) => {
);
}
if (error) {
return (
<main className="flex items-center justify-center min-h-screen">
<div className="flex flex-col gap-2">
<h1 className="text-2xl font-bold">Ошибка</h1>
<p className="text-lg">
Произошла ошибка при загрузке профиля. Попробуйте обновить страницу
или зайдите позже.
</p>
</div>
</main>
);
}
const hasSocials =
user.vk_page != "" ||
user.tg_page != "" ||
@ -157,7 +158,11 @@ export const ProfilePage = (props: any) => {
{!user.is_stats_hidden && (
<div className="flex-col hidden gap-2 xl:flex">
{user.votes && user.votes.length > 0 && (
<ProfileReleaseRatings ratings={user.votes} token={authUser.token} profile_id={user.id} />
<ProfileReleaseRatings
ratings={user.votes}
token={authUser.token}
profile_id={user.id}
/>
)}
{user.history && user.history.length > 0 && (
<ProfileReleaseHistory history={user.history} />
@ -197,7 +202,11 @@ export const ProfilePage = (props: any) => {
<ProfileWatchDynamic watchDynamic={user.watch_dynamics || []} />
<div className="flex flex-col gap-2 xl:hidden">
{user.votes && user.votes.length > 0 && (
<ProfileReleaseRatings ratings={user.votes} token={authUser.token} profile_id={user.id} />
<ProfileReleaseRatings
ratings={user.votes}
token={authUser.token}
profile_id={user.id}
/>
)}
{user.history && user.history.length > 0 && (
<ProfileReleaseHistory history={user.history} />
@ -207,7 +216,12 @@ export const ProfilePage = (props: any) => {
)}
</div>
</div>
<ProfileEditModal isOpen={isOpen && isMyProfile} setIsOpen={setIsOpen} token={authUser.token} profile_id={user.id}/>
<ProfileEditModal
isOpen={isOpen && isMyProfile}
setIsOpen={setIsOpen}
token={authUser.token}
profile_id={user.id}
/>
</>
);
};

View file

@ -16,19 +16,26 @@ export async function generateMetadata(
parent: ResolvingMetadata
): Promise<Metadata> {
const id: string = params.id;
const profile: any = await fetchDataViaGet(
const { data, error } = await fetchDataViaGet(
`https://api.anixart.tv/profile/${id}`
);
const previousOG = (await parent).openGraph;
if (error) {
return {
title: SectionTitleMapping[params.slug] + " - " + profile.profile.login,
description: profile.profile.status,
title: "Ошибка",
description: "Ошибка",
};
};
return {
title:"Закладки Пользователя - " + data.profile.login + " - " + SectionTitleMapping[params.slug],
description: "Закладки Пользователя - " + data.profile.login + " - " + SectionTitleMapping[params.slug],
openGraph: {
...previousOG,
images: [
{
url: profile.profile.avatar, // Must be an absolute URL
url: data.profile.avatar, // Must be an absolute URL
width: 600,
height: 600,
},

View file

@ -1,26 +1,33 @@
import { BookmarksPage } from "#/pages/Bookmarks";
import { fetchDataViaGet } from "#/api/utils";
import type { Metadata, ResolvingMetadata } from "next";
export const dynamic = 'force-static';
export const dynamic = "force-static";
export async function generateMetadata(
{ params },
parent: ResolvingMetadata
): Promise<Metadata> {
const id: string = params.id;
const profile: any = await fetchDataViaGet(
const { data, error } = await fetchDataViaGet(
`https://api.anixart.tv/profile/${id}`
);
const previousOG = (await parent).openGraph;
if (error) {
return {
title: "Закладки - " + profile.profile.login,
description: profile.profile.status,
title: "Ошибка",
description: "Ошибка",
};
};
return {
title: "Закладки Пользователя - " + data.profile.login,
description: "Закладки Пользователя - " + data.profile.login,
openGraph: {
...previousOG,
images: [
{
url: profile.profile.avatar, // Must be an absolute URL
url: data.profile.avatar, // Must be an absolute URL
width: 600,
height: 600,
},

View file

@ -1,43 +1,65 @@
import { CollectionsFullPage } from "#/pages/CollectionsFull";
import { fetchDataViaGet } from "#/api/utils";
import type { Metadata, ResolvingMetadata } from "next";
export const dynamic = 'force-static';
export const dynamic = "force-static";
export async function generateMetadata(
{ params },
parent: ResolvingMetadata
): Promise<Metadata> {
const id: string = params.id;
const profile: any = await fetchDataViaGet(
const { data, error } = await fetchDataViaGet(
`https://api.anixart.tv/profile/${id}`
);
const previousOG = (await parent).openGraph;
if (error) {
return {
title: "Коллекции - " + profile.profile.login,
description: profile.profile.status,
title: "Ошибка",
description: "Ошибка",
};
};
return {
title: "Коллекции Пользователя - " + data.profile.login,
description: "Коллекции Пользователя - " + data.profile.login,
openGraph: {
...previousOG,
images: [
{
url: profile.profile.avatar, // Must be an absolute URL
url: data.profile.avatar, // Must be an absolute URL
width: 600,
height: 600,
},
],
},
};
}
};
export default async function Collections({ params }) {
const profile: any = await fetchDataViaGet(
const { data, error } = await fetchDataViaGet(
`https://api.anixart.tv/profile/${params.id}`
);
if (error) {
return (
<main className="flex items-center justify-center min-h-screen">
<div className="flex flex-col gap-2">
<h1 className="text-2xl font-bold">Ошибка</h1>
<p className="text-lg">
Произошла ошибка при загрузке коллекций пользователя. Попробуйте
обновить страницу или зайдите позже.
</p>
</div>
</main>
);
}
return (
<CollectionsFullPage
type="profile"
title={`Коллекции пользователя ${profile.profile.login}`}
title={`Коллекции пользователя: ${data.profile.login}`}
profile_id={params.id}
/>
);
}
};

View file

@ -1,26 +1,33 @@
import { ProfilePage } from "#/pages/Profile";
import { fetchDataViaGet } from "#/api/utils";
import type { Metadata, ResolvingMetadata } from "next";
export const dynamic = 'force-static';
export const dynamic = "force-static";
export async function generateMetadata(
{ params },
parent: ResolvingMetadata
): Promise<Metadata> {
const id: string = params.id;
const profile: any = await fetchDataViaGet(
const { data, error } = await fetchDataViaGet(
`https://api.anixart.tv/profile/${id}`
);
const previousOG = (await parent).openGraph;
if (error) {
return {
title: "Профиль - " + profile.profile.login,
description: profile.profile.status,
title: "Ошибка",
description: "Ошибка",
};
}
return {
title: "Профиль - " + data.profile.login,
description: data.profile.status,
openGraph: {
...previousOG,
images: [
{
url: profile.profile.avatar, // Must be an absolute URL
url: data.profile.avatar, // Must be an absolute URL
width: 600,
height: 600,
},

View file

@ -44,14 +44,16 @@ export const useUserStore = create<userState>((set, get) => ({
const jwt = getJWT();
if (jwt) {
const _checkAuth = async () => {
const data = await fetchDataViaGet(
const { data, error } = await fetchDataViaGet(
`${ENDPOINTS.user.profile}/${jwt.user_id}?token=${jwt.jwt}`
);
if (data && data.is_my_profile) {
get().login(data.profile, jwt.jwt);
} else {
if (error || !data.is_my_profile) {
get().logout();
return;
}
get().login(data.profile, jwt.jwt);
};
_checkAuth();
} else {

View file

@ -18,10 +18,13 @@ export default async function middleware(
}
let path = url.pathname.match(/\/api\/proxy\/(.*)/)?.[1] + url.search;
const data = await fetchDataViaGet(`${API_URL}/${path}`, isApiV2);
const { data, error } = await fetchDataViaGet(
`${API_URL}/${path}`,
isApiV2
);
if (!data) {
return new Response(JSON.stringify({ message: "Error Fetching Data" }), {
if (error) {
return new Response(JSON.stringify(error), {
status: 500,
headers: {
"Content-Type": "application/json",