Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"@tanstack/react-query": "^5.90.7",
"@tanstack/react-query-devtools": "^5.90.2",
"clsx": "^2.1.1",
"cookie": "^1.0.2",
"date-fns": "^4.1.0",
"mock-socket": "^9.3.1",
"next": "15.5.3",
Expand Down
58 changes: 58 additions & 0 deletions src/app/api/auth/login/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import * as cookie from "cookie";

const BASE_URL = process.env.NEXT_PUBLIC_API_URL;

export async function POST(req: Request) {
const { email, password } = await req.json();

const backendRes = await fetch(`${BASE_URL}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});

if (!backendRes.ok) {
const errorData = await backendRes.json();
return NextResponse.json(errorData, { status: backendRes.status });
}

const { accessToken } = await backendRes.json();

const cookieHandler = await cookies();

const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
path: "/",
};

cookieHandler.set({
name: "accessToken",
value: accessToken,
...cookieOptions,
maxAge: 60 * 60 * 2,
});

const setCookieHeaders = backendRes.headers.getSetCookie?.() ?? [];

for (const c of setCookieHeaders) {
const parsed = cookie.parse(c);

if (parsed.refreshToken) {
const maxAge = parsed["Max-Age"]
? parseInt(parsed["Max-Age"], 10)
: 60 * 60 * 24 * 30;

cookieHandler.set({
name: "refreshToken",
value: parsed.refreshToken,
...cookieOptions,
maxAge,
});
}
}

return NextResponse.json({ message: "Login successful", accessToken });
}
10 changes: 10 additions & 0 deletions src/app/api/auth/logout/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { NextResponse } from "next/server";

export async function POST() {
const res = NextResponse.json({ message: "Logged out successfully" });

res.cookies.delete("accessToken");
res.cookies.delete("refreshToken");

return res;
}
70 changes: 70 additions & 0 deletions src/app/api/auth/refresh/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import * as cookie from "cookie";

const BASE_URL = process.env.NEXT_PUBLIC_API_URL;

export async function POST() {
const cookieHandler = await cookies();
const refreshToken = cookieHandler.get("refreshToken")?.value;

if (!refreshToken) {
return NextResponse.json(
{ message: "No refresh token provided" },
{ status: 401 },
);
}

const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
path: "/",
};

const backendRes = await fetch(`${BASE_URL}/auth/refresh`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Cookie: `refreshToken=${refreshToken}`,
},
});

if (!backendRes.ok) {
return NextResponse.json(
{ message: "Invalid refresh token" },
{ status: 401 },
);
}

const { accessToken } = await backendRes.json();

const res = NextResponse.json({ accessToken });

cookieHandler.set({
name: "accessToken",
value: accessToken,
...cookieOptions,
maxAge: 60 * 60 * 2,
});

const setCookieHeaders = backendRes.headers.getSetCookie?.() ?? [];

for (const c of setCookieHeaders) {
const parsed = cookie.parse(c);

if (parsed.refreshToken) {
const maxAge = parsed["Max-Age"]
? parseInt(parsed["Max-Age"], 10)
: 60 * 60 * 24 * 30;

cookieHandler.set({
name: "refreshToken",
value: parsed.refreshToken,
...cookieOptions,
maxAge,
});
}
}

return res;
}
14 changes: 12 additions & 2 deletions src/app/detail/[postingId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import {
dehydrate,
HydrationBoundary,
} from "@tanstack/react-query";
import { getPostDetail } from "@/entities/post/api/getPostDetail";
import { getPostDetail } from "@/entities/post/api/getPostDetail.server";
import { getUser } from "@/entities/user/api/getUser.server";
import PostDetailPageClient from "@/widgets/postDetail/ui/DetailPage.client";
import type { PostDetail } from "@/entities/post/model/types/post";

export default async function Page({
params,
Expand All @@ -18,9 +20,17 @@ export default async function Page({
await queryClient.prefetchQuery({
queryKey: ["postDetail", id],
queryFn: () => getPostDetail(id),
staleTime: Infinity,
});

const post = queryClient.getQueryData<PostDetail>(["postDetail", id]);

if (post && post.sellerId) {
await queryClient.prefetchQuery({
queryKey: ["seller", post.sellerId],
queryFn: () => getUser(post.sellerId),
});
}

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<PostDetailPageClient postingId={postingId} />
Expand Down
143 changes: 18 additions & 125 deletions src/app/my/page.tsx
Original file line number Diff line number Diff line change
@@ -1,138 +1,31 @@
"use client";
import {
HydrationBoundary,
QueryClient,
dehydrate,
} from "@tanstack/react-query";

import { useState, useCallback } from "react";
import { useQuery } from "@tanstack/react-query";
import Profile, { ProfileProps } from "@/entities/user/ui/card/Profile";
import ProfileSkeleton from "@/entities/user/ui/card/ProfileSkeleton";
import PostCard from "@/entities/post/ui/card/PostCard";
import { PostCreateButton } from "@/features/createPost/ui/PostCreateButton/PostCreateButton";
import Tab from "@/widgets/mypage/ui/Tab.tsx/Tab";
import { useModalStore } from "@/shared/model/modal.store";
import { usePostCreateModal } from "@/features/createPost/lib/usePostCreateModal";
import { getMyPosts, getMyProfile } from "@/entities/user/api/mypage";
import type { Post } from "@/entities/post/model/types/post";
import { PostStatus } from "@/entities/post/model/types/post";
import { getMyPosts } from "@/entities/user/api/getMyPosts.server";
import { getMyProfile } from "@/entities/user/api/getMyProfile.server";
import MyPageClient from "@/widgets/mypage/ui/Client/MyPage.client";

const options = [
{ label: "판매중 상품", value: "selling" },
{ label: "판매완료 상품", value: "sold" },
{ label: "구매한 상품", value: "purchased" },
{ label: "관심 상품", value: "favorite" },
];
const DEFAULT_TAB = "selling";

const emptyMessageMap: Record<string, string> = {
selling: "등록되어 있는 상품이 없습니다.",
sold: "판매 완료된 상품이 없습니다.",
purchased: "구매 완료된 상품이 없습니다.",
favorite: "즐겨찾기한 상품이 없습니다.",
};
interface PostListItem {
postingId: number;
sellerId: number;
title: string;
price: number;
content: string;
category: string;
createdAt: string;
likeCount: number;
chatCount: number;
viewCount: number;
thumbnail: string;
status: PostStatus;
}

export default function Page() {
const [selectedTab, setSelectedTab] = useState(options[0].value);
const { openModal, closeModal } = useModalStore();
export default async function Page() {
const queryClient = new QueryClient();

const {
data: userProfile,
isLoading: profileLoading,
refetch: refetchUserProfile,
} = useQuery<ProfileProps>({
await queryClient.prefetchQuery({
queryKey: ["userProfile"],
queryFn: getMyProfile,
});

const {
data: postsData,
isLoading: postsLoading,
refetch: refetchPosts,
} = useQuery<{ data: Post[] }>({
queryKey: ["myPosts", selectedTab],
queryFn: () => getMyPosts(selectedTab),
await queryClient.prefetchQuery({
queryKey: ["myPosts", DEFAULT_TAB],
queryFn: () => getMyPosts(DEFAULT_TAB),
});

const { openPostCreateModal } = usePostCreateModal({
onSuccess: async () => {
await refetchPosts();
},
});

const handleEditProfile = useCallback(() => {
if (!userProfile) return;

openModal("editProfile", {
...userProfile,
onClose: () => closeModal(),
onSave: async () => {
closeModal();
setTimeout(() => {
openModal("normal", {
message: "프로필이 성공적으로 수정되었습니다.",
buttonText: "확인",
onClick: () => {
closeModal();
},
});
}, 100);
await refetchUserProfile();
},
onError: () => {
closeModal();
openModal("normal", {
message: "프로필 수정에 실패했습니다.",
buttonText: "확인",
onClick: () => {
closeModal();
},
});
},
});
}, [userProfile, openModal, closeModal, refetchUserProfile]);

const posts = postsData?.data || [];

return (
<main className="m-auto flex max-w-[335px] flex-col items-center justify-center gap-[60px] py-[30px] md:max-w-[510px] md:py-10 xl:max-w-[1340px] xl:flex-row xl:items-start xl:justify-start xl:gap-20 xl:py-[60px]">
{profileLoading || !userProfile ? (
<ProfileSkeleton />
) : (
<Profile {...userProfile} onEdit={handleEditProfile} />
)}

<section className="flex flex-col gap-[30px]">
<Tab
options={options}
selected={selectedTab}
onChange={setSelectedTab}
/>

{postsLoading ? null : posts.length === 0 ? (
<p className="mt-10 text-center text-gray-400">
{emptyMessageMap[selectedTab]}
</p>
) : (
<ul className="grid grid-cols-2 gap-[15px] xl:grid-cols-3 xl:gap-5">
{posts.map((post) => (
<li key={post.postingId}>
<PostCard {...post} />
</li>
))}
</ul>
)}
<PostCreateButton onClick={openPostCreateModal} />
</section>
</main>
<HydrationBoundary state={dehydrate(queryClient)}>
<MyPageClient defaultTab={DEFAULT_TAB} />
</HydrationBoundary>
);
}
2 changes: 1 addition & 1 deletion src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
dehydrate,
HydrationBoundary,
} from "@tanstack/react-query";
import { getPosts } from "@/entities/post/api/getPosts";
import { getPosts } from "@/entities/post/api/getPosts.server";
import HomePageClient from "@/widgets/main/ui/Client/HomePage.client";

export default async function Page({
Expand Down
10 changes: 10 additions & 0 deletions src/entities/post/api/getPostDetail.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { serverFetch } from "@/shared/api/fetcher.server";
import type { PostDetail } from "../model/types/post";

export async function getPostDetail(postingId: number): Promise<PostDetail> {
if (!postingId) throw new Error("Invalid postingId");

return serverFetch<PostDetail>(`/api/postings/${postingId}`, {
method: "GET",
});
}
Loading