fix forum

This commit is contained in:
2025-02-14 09:06:22 +08:00
parent f9e72a51bb
commit eb335533eb
11 changed files with 350 additions and 59 deletions

View File

@@ -2,7 +2,7 @@ import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc"; import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const dirname = dirname(filename); const dirname = dirname(__filename);
const compat = new FlatCompat({ const compat = new FlatCompat({
baseDirectory: __dirname, baseDirectory: __dirname,

124
src/app/api/forum/route.ts Normal file
View File

@@ -0,0 +1,124 @@
import { prisma } from "@/lib";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
// GET ALL DATA PORTOFOLIO BY PROFILE ID
export async function GET(request: Request) {
try {
let fixData;
const { searchParams } = new URL(request.url);
const page = searchParams.get("page");
const search = searchParams.get("search");
const takeData = 4
const skipData = Number(page) * takeData - takeData;
if (!page) {
fixData = await prisma.forum_Posting.findMany({
orderBy: {
createdAt: "desc",
},
where: {
isActive: true,
diskusi: {
mode: "insensitive",
contains: search == undefined || search == "null" ? "" : search,
},
},
select: {
id: true,
diskusi: true,
createdAt: true,
isActive: true,
authorId: true,
Author: {
select: {
id: true,
username: true,
Profile: {
select: {
id: true,
name: true,
imageId: true,
},
},
},
},
Forum_Komentar: {
where: {
isActive: true,
},
},
ForumMaster_StatusPosting: {
select: {
id: true,
status: true,
},
},
forumMaster_StatusPostingId: true,
},
});
} else {
fixData = await prisma.forum_Posting.findMany({
take: takeData,
skip: skipData,
orderBy: {
createdAt: "desc",
},
where: {
isActive: true,
diskusi: {
mode: "insensitive",
contains: search == undefined || search == "null" ? "" : search,
},
},
select: {
id: true,
diskusi: true,
createdAt: true,
isActive: true,
authorId: true,
Author: {
select: {
id: true,
username: true,
Profile: {
select: {
id: true,
name: true,
imageId: true,
},
},
},
},
Forum_Komentar: {
where: {
isActive: true,
},
},
ForumMaster_StatusPosting: {
select: {
id: true,
status: true,
},
},
forumMaster_StatusPostingId: true,
},
});
}
return NextResponse.json(
{ success: true, message: "Berhasil mendapatkan data", data: fixData },
{ status: 200 }
);
} catch (error) {
console.error(error);
return NextResponse.json(
{
success: false,
message: "Gagal mendapatkan data, coba lagi nanti ",
reason: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,34 @@
import backendLogger from "@/util/backendLogger";
import { NextResponse } from "next/server";
export async function GET(
request: Request,
{ params }: { params: { id: string } }
) {
try {
const { id } = params;
const data = await prisma.user.findUnique({
where: {
id: id,
},
include: {
Profile: true,
},
});
return NextResponse.json(
{ success: true, message: "Berhasil mendapatkan data", data: data },
{ status: 200 }
);
} catch (error) {
backendLogger.error("Error get data user", error);
return NextResponse.json(
{
success: false,
message: "Gagal mendapatkan data, coba lagi nanti ",
reason: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -1,6 +1,5 @@
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get"; import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { LayoutForum_Main } from "@/app_modules/forum"; import { LayoutForum_Main } from "@/app_modules/forum";
import { user_getOneByUserId } from "@/app_modules/home/fun/get/get_one_user_by_id";
import React from "react"; import React from "react";
export default async function Layout({ export default async function Layout({
@@ -9,13 +8,11 @@ export default async function Layout({
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const userLoginId = await funGetUserIdByToken(); const userLoginId = await funGetUserIdByToken();
const dataAuthor = await user_getOneByUserId(userLoginId as string);
return ( return (
<> <>
<LayoutForum_Main dataAuthor={dataAuthor as any}> <LayoutForum_Main userLoginId={userLoginId}>{children}</LayoutForum_Main>
{children}
</LayoutForum_Main>
</> </>
); );
} }

View File

@@ -1,17 +1,12 @@
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get"; import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { Forum_Beranda } from "@/app_modules/forum"; import { Forum_Beranda } from "@/app_modules/forum";
import { forum_new_getAllPosting } from "@/app_modules/forum/fun/get/new_get_all_posting";
export default async function Page() { export default async function Page() {
const userLoginId = await funGetUserIdByToken(); const userLoginId = await funGetUserIdByToken();
const listForum = await forum_new_getAllPosting({ page: 1 });
return ( return (
<> <>
<Forum_Beranda <Forum_Beranda userLoginId={userLoginId as string} />
listForum={listForum as any}
userLoginId={userLoginId as string}
/>
</> </>
); );
} }

View File

@@ -1,3 +1,4 @@
import { apiGetUserProfile } from './../../user/lib/api_user';
export const apiGetUserId = async () => { export const apiGetUserId = async () => {
const { token } = await fetch("/api/get-cookie").then((res) => res.json()); const { token } = await fetch("/api/get-cookie").then((res) => res.json());
if (!token) return await token.json().catch(() => null); if (!token) return await token.json().catch(() => null);
@@ -58,3 +59,43 @@ export const apiGetAllUserWithExceptId = async ({
}); });
return await response.json().catch(() => null); return await response.json().catch(() => null);
}; };
export const apiGetUserById = async ({ id }: { id: string }) => {
try {
// Fetch token from cookie
const { token } = await fetch("/api/get-cookie").then((res) => res.json());
if (!token) {
console.error("No token found");
return null;
}
// Send PUT request to update portfolio logo
const response = await fetch(`/api/user/${id}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
});
// Check if the response is OK
if (!response.ok) {
const errorData = await response.json().catch(() => null);
console.error(
"Failed to get user",
response.statusText,
errorData
);
throw new Error(
errorData?.message || "Failed to get user"
);
}
// Return the JSON response
return await response.json();
} catch (error) {
console.error("Error get user:", error);
throw error; // Re-throw the error to handle it in the calling function
}
};

View File

@@ -0,0 +1,41 @@
export { apiGetAllForum };
const apiGetAllForum = async ({
page,
search,
}: {
page: string;
search?: string;
}) => {
try {
// Fetch token from cookie
const { token } = await fetch("/api/get-cookie").then((res) => res.json());
if (!token) {
console.error("No token found");
return null;
}
const isSearch = search ? `&search=${search}` : "";
const response = await fetch(`/api/forum?page=${page}${isSearch}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
});
// Check if the response is OK
if (!response.ok) {
const errorData = await response.json().catch(() => null);
console.error("Failed to get all forum:", response.statusText, errorData);
throw new Error(errorData?.message || "Failed to get all forum");
}
// Return the JSON response
return await response.json();
} catch (error) {
console.error("Error get all forum", error);
throw error; // Re-throw the error to handle it in the calling function
}
};

View File

@@ -23,35 +23,42 @@ import { useState } from "react";
import ComponentForum_BerandaCardView from "../component/main_component/card_view"; import ComponentForum_BerandaCardView from "../component/main_component/card_view";
import { forum_new_getAllPosting } from "../fun/get/new_get_all_posting"; import { forum_new_getAllPosting } from "../fun/get/new_get_all_posting";
import { MODEL_FORUM_POSTING } from "../model/interface"; import { MODEL_FORUM_POSTING } from "../model/interface";
import { apiGetAllForum } from "../component/api_fetch_forum";
import { clientLogger } from "@/util/clientLogger";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
export default function Forum_Beranda({ export default function Forum_Beranda({
listForum,
userLoginId, userLoginId,
}: { }: {
listForum: any;
userLoginId: string; userLoginId: string;
}) { }) {
const router = useRouter(); const router = useRouter();
const [scroll, scrollTo] = useWindowScroll(); const [scroll, scrollTo] = useWindowScroll();
const [data, setData] = useState<MODEL_FORUM_POSTING[]>(listForum); const [data, setData] = useState<MODEL_FORUM_POSTING[] | null>(null);
const [activePage, setActivePage] = useState(1); const [activePage, setActivePage] = useState(1);
const [isSearch, setIsSearch] = useState(""); const [isSearch, setIsSearch] = useState("");
const [isNewPost, setIsNewPost] = useState(false); const [isNewPost, setIsNewPost] = useState(false);
const [countNewPost, setCountNewPost] = useState(0); const [countNewPost, setCountNewPost] = useState(0);
useShallowEffect(() => { useShallowEffect(() => {
onLoadAllData({ handleLoadData(isSearch);
onLoad(val) { }, [isSearch]);
setData(val);
},
});
}, [setData]);
async function onLoadAllData({ onLoad }: { onLoad: (val: any) => void }) { const handleLoadData = async (isSearch: string) => {
const loadData = await forum_new_getAllPosting({ page: 1 }); try {
onLoad(loadData); const response = await apiGetAllForum({
} page: `${activePage}`,
search: isSearch,
});
if (response) {
setData(response.data);
}
} catch (error) {
clientLogger.error("Error get data forum", error);
}
};
useShallowEffect(() => { useShallowEffect(() => {
mqtt_client.subscribe("Forum_create_new"); mqtt_client.subscribe("Forum_create_new");
@@ -83,7 +90,7 @@ export default function Forum_Beranda({
if (topic === "Forum_detail_ganti_status") { if (topic === "Forum_detail_ganti_status") {
const newData = JSON.parse(message.toString()); const newData = JSON.parse(message.toString());
const updateOneData = cloneData.map((val) => ({ const updateOneData = cloneData?.map((val) => ({
...val, ...val,
ForumMaster_StatusPosting: { ForumMaster_StatusPosting: {
id: id:
@@ -104,12 +111,8 @@ export default function Forum_Beranda({
async function onSearch(text: string) { async function onSearch(text: string) {
setIsSearch(text); setIsSearch(text);
const loadSearch = await forum_new_getAllPosting({
page: activePage,
search: text,
});
setData(loadSearch as any);
setActivePage(1); setActivePage(1);
} }
return ( return (
@@ -133,6 +136,7 @@ export default function Forum_Beranda({
<Stack spacing={"xl"}> <Stack spacing={"xl"}>
<TextInput <TextInput
disabled={!data}
radius={"xl"} radius={"xl"}
placeholder="Topik forum apa yang anda cari hari ini ?" placeholder="Topik forum apa yang anda cari hari ini ?"
onChange={(val) => { onChange={(val) => {
@@ -140,7 +144,12 @@ export default function Forum_Beranda({
}} }}
/> />
{_.isEmpty(data) ? ( {!data ? (
<Stack>
<CustomSkeleton height={230} width={"100%"} />
<CustomSkeleton height={230} width={"100%"} />
</Stack>
) : _.isEmpty(data) ? (
<Stack align="center" justify="center" h={"80vh"}> <Stack align="center" justify="center" h={"80vh"}>
<IconSearchOff size={80} color="white" /> <IconSearchOff size={80} color="white" />
<Stack spacing={0} align="center"> <Stack spacing={0} align="center">
@@ -159,15 +168,22 @@ export default function Forum_Beranda({
</Center> </Center>
)} )}
data={data} data={data}
setData={setData} setData={setData as any}
moreData={async () => { moreData={async () => {
const loadData = await forum_new_getAllPosting({ try {
page: activePage + 1, const nextPage = activePage + 1;
search: isSearch, const response = await apiGetAllForum({
}); page: `${nextPage}`,
setActivePage((val) => val + 1); search: isSearch,
});
return loadData; if (response) {
setActivePage((val) => val + 1);
return response.data;
}
} catch (error) {
clientLogger.error("Error get data forum", error);
}
}} }}
> >
{(item) => ( {(item) => (

View File

@@ -9,17 +9,39 @@ import { MODEL_USER } from "@/app_modules/home/model/interface";
import { ActionIcon, Avatar } from "@mantine/core"; import { ActionIcon, Avatar } from "@mantine/core";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import React, { useState } from "react"; import React, { useState } from "react";
import { useShallowEffect } from "@mantine/hooks";
import { apiGetUserById } from "@/app_modules/_global/lib/api_user";
import { clientLogger } from "@/util/clientLogger";
export default function LayoutForum_Main({ export default function LayoutForum_Main({
userLoginId,
children, children,
dataAuthor,
}: { }: {
userLoginId: string;
children: React.ReactNode; children: React.ReactNode;
dataAuthor: MODEL_USER;
}) { }) {
const router = useRouter(); const router = useRouter();
const [data, setData] = useState<MODEL_USER | null>(null);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
useShallowEffect(() => {
handleLoadData();
}, []);
const handleLoadData = async () => {
try {
const response = await apiGetUserById({
id: userLoginId,
});
if (response) {
setData(response.data);
}
} catch (error) {
clientLogger.error("Error get user", error);
}
};
return ( return (
<> <>
<UIGlobal_LayoutTamplate <UIGlobal_LayoutTamplate
@@ -27,15 +49,14 @@ export default function LayoutForum_Main({
<UIGlobal_LayoutHeaderTamplate <UIGlobal_LayoutHeaderTamplate
title="Forum" title="Forum"
iconRight={ iconRight={
<ActionIcon !data ? (
radius={"xl"} <ActionIcon
variant="transparent" radius={"xl"}
onClick={() => { variant="transparent"
setIsLoading(true); onClick={() => {
router.push(RouterForum.forumku + dataAuthor?.id); return null;
}} }}
> >
{isLoading ? (
<Avatar <Avatar
size={30} size={30}
radius={"100%"} radius={"100%"}
@@ -47,13 +68,36 @@ export default function LayoutForum_Main({
> >
<ComponentGlobal_Loader variant="dots" /> <ComponentGlobal_Loader variant="dots" />
</Avatar> </Avatar>
) : ( </ActionIcon>
<ComponentGlobal_LoaderAvatar ) : (
fileId={dataAuthor.Profile.imageId as any} <ActionIcon
sizeAvatar={30} radius={"xl"}
/> variant="transparent"
)} onClick={() => {
</ActionIcon> setIsLoading(true);
router.push(RouterForum.forumku + data?.id);
}}
>
{isLoading ? (
<Avatar
size={30}
radius={"100%"}
style={{
borderColor: "white",
borderStyle: "solid",
borderWidth: "1px",
}}
>
<ComponentGlobal_Loader variant="dots" />
</Avatar>
) : (
<ComponentGlobal_LoaderAvatar
fileId={data.Profile.imageId as any}
sizeAvatar={30}
/>
)}
</ActionIcon>
)
} }
/> />
} }

View File

@@ -65,8 +65,6 @@ export function ComponentMap_ButtonSavePin({
data: newData, data: newData,
}); });
console.log("respone >", respone);
if (respone && respone.success) { if (respone && respone.success) {
ComponentGlobal_NotifikasiBerhasil(respone.message); ComponentGlobal_NotifikasiBerhasil(respone.message);
router.back(); router.back();

View File

@@ -34,6 +34,7 @@ const middlewareConfig: MiddlewareConfig = {
// ADMIN API // ADMIN API
// >> buat dibawah sini << // >> buat dibawah sini <<
"/api/user",