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
44 changes: 36 additions & 8 deletions src/api/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { HTTPSTATUS } from "./types";

type FetcherOptions = RequestInit & {
headers?: HeadersInit;
cookies?: Record<string, string>;
};

type FetcherResponse<T> = {
Expand Down Expand Up @@ -40,6 +41,23 @@ const handleError = async (response: Response) => {
throw new Error(`HTTP error! status: ${response.status}`);
};

// 쿠키를 헤더에 추가
const addCookiesToHeaders = (
headers: HeadersInit = {},
cookies?: Record<string, string>
): HeadersInit => {
if (!cookies) return headers;

const cookieString = Object.entries(cookies)
.map(([key, value]) => `${key}=${value}`)
.join("; ");

return {
...headers,
Cookie: cookieString,
};
};

// 데이터를 받지 않는 요청 (GET, DELETE)
const requestWithoutData = async <T>(
url: string,
Expand All @@ -49,10 +67,13 @@ const requestWithoutData = async <T>(
const fetchOptions: FetcherOptions = {
...options,
method,
headers: {
"Content-Type": "application/json",
...(options.headers || {}),
},
headers: addCookiesToHeaders(
{
"Content-Type": "application/json",
...(options.headers || {}),
},
options.cookies
),
};
const response = await fetch(url, fetchOptions);

Expand All @@ -75,10 +96,13 @@ const requestWithData = async <T>(
const fetchOptions: FetcherOptions = {
...options,
method,
headers: {
"Content-Type": "application/json",
...(options?.headers || {}),
},
headers: addCookiesToHeaders(
{
"Content-Type": "application/json",
...(options?.headers || {}),
},
options?.cookies
),
...(data ? { body: JSON.stringify(data) } : {}),
};

Expand Down Expand Up @@ -157,6 +181,10 @@ export const proxyFetcher = createFetcher(`${BASE_API_URL}/api`, {
credentials: "include",
});

export const clientFetcher = createFetcher(`${CLIENT_URL}/api`, {
credentials: "include",
});

export const fetcherWithoutCredentials = createFetcher(`${BASE_API_URL}/api`, {
credentials: "omit",
});
11 changes: 5 additions & 6 deletions src/components/Header/desktop/HeaderTopD.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,19 @@ import { PortfoliosDropdown } from "@/components/PortfoliosDropdown/PortfoliosDr
import SearchBarD from "@/components/SearchBar/desktop/SearchBarD";
import Routes from "@/constants/Routes";
import { MAIN_HEADER_HEIGHT_D } from "@/constants/styleConstants";
import useAuthStatusQuery from "@/features/auth/api/queries/useAuthStatusQuery";
import UserControls from "@/features/user/components/desktop/UserControls";
import { UserContext } from "@/features/user/context/UserContext";
import Image from "next/image";
import Link from "next/link";
import { useContext } from "react";
import styled from "styled-components";

export default function HeaderTopD() {
const { user } = useContext(UserContext);
const { data: isLoggedIn } = useAuthStatusQuery();

const navItems = [
{
name: "Watchlists",
to: user ? Routes.WATCHLISTS : Routes.SIGNIN,
to: isLoggedIn ? Routes.WATCHLISTS : Routes.SIGNIN,
},
{ name: "Indices", to: Routes.INDICES("KRX:KOSPI") },
];
Expand All @@ -28,7 +27,7 @@ export default function HeaderTopD() {
<StyledHeaderTopD>
<HeaderLeft>
<StyledBrandIdentityLink
href={user ? Routes.DASHBOARD : Routes.LANDING}>
href={isLoggedIn ? Routes.DASHBOARD : Routes.LANDING}>
<Image width={127} height={24} src={BIImage.src} alt="FineAnts" />
</StyledBrandIdentityLink>
<NavBar>
Expand All @@ -43,7 +42,7 @@ export default function HeaderTopD() {
<HeaderRight>
<SearchBarD sx={{ width: "328px" }} />

{user ? (
{isLoggedIn ? (
<UserControls />
) : (
<ButtonWrapper>
Expand Down
11 changes: 4 additions & 7 deletions src/components/Layout.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
import Routes from "@/constants/Routes";
import dynamic from "next/dynamic";
import { usePathname } from "next/navigation";
import { ReactNode } from "react";
import Header from "./Header/Header";

const Header = dynamic(import("./Header/Header"), {
ssr: false,
});
type LayoutProps = { children: ReactNode };

export default function Layout({ children }: { children: ReactNode }) {
export default function Layout({ children }: LayoutProps) {
const pathname = usePathname();

// TODO : Layout을 제외해야 하는 페이지가 더 늘어난다면 개선하기
if (pathname === Routes.SIGNIN || pathname === Routes.SIGNUP) {
return children;
return <>{children}</>;
}

return (
Expand Down
9 changes: 9 additions & 0 deletions src/features/auth/api/apiRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { clientFetcher } from "@/api/fetcher";
import { Response } from "@/api/types";

export const getAuthStatus = async (cookies?: Record<string, string>) => {
const res = await clientFetcher.get<Response<boolean>>("/authStatus", {
cookies,
});
return res.data;
};
5 changes: 5 additions & 0 deletions src/features/auth/api/queries/queryKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createQueryKeys } from "@lukemorales/query-key-factory";

export const authKeys = createQueryKeys("auth", {
authStatus: null,
});
14 changes: 14 additions & 0 deletions src/features/auth/api/queries/useAuthStatusQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useSuspenseQuery } from "@tanstack/react-query";
import { getAuthStatus } from "../apiRoutes";
import { authKeys } from "./queryKeys";

export default function useAuthStatusQuery(cookies?: Record<string, string>) {
return useSuspenseQuery({
queryKey: authKeys.authStatus.queryKey,
queryFn: () => getAuthStatus(cookies),
select: (res) => res.data,
retry: 0,
gcTime: Infinity,
staleTime: Infinity,
});
}
22 changes: 10 additions & 12 deletions src/features/auth/api/queries/useSignInMutation.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,28 @@
import Routes from "@/constants/Routes";
import { getUser } from "@/features/user/api";
import { UserContext } from "@/features/user/context/UserContext";
import { useMutation } from "@tanstack/react-query";
import { userKeys } from "@/features/user/api/queries/queryKeys";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/router";
import { useContext } from "react";
import { postSignIn } from "../index";
import { authKeys } from "./queryKeys";

export default function useSignInMutation() {
const router = useRouter();
const { onSignOut, onGetUser } = useContext(UserContext);
const queryClient = useQueryClient();

return useMutation({
mutationFn: postSignIn,
onSuccess: async () => {
try {
const {
data: { user },
} = await getUser();

onGetUser(user);

router.push(Routes.DASHBOARD);
queryClient.invalidateQueries({
queryKey: authKeys.authStatus.queryKey,
});
queryClient.invalidateQueries({
queryKey: userKeys.userInfo.queryKey,
});
} catch (error) {
// eslint-disable-next-line no-console
console.error("Failed to fetch user data");
onSignOut();
router.push(Routes.SIGNIN);
}
},
Expand Down
15 changes: 10 additions & 5 deletions src/features/auth/api/queries/useSignOutMutation.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
import Routes from "@/constants/Routes";
import { UserContext } from "@/features/user/context/UserContext";
import { useMutation } from "@tanstack/react-query";
import { userKeys } from "@/features/user/api/queries/queryKeys";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/router";
import { useContext } from "react";
import { postSignOut } from "..";
import { authKeys } from "./queryKeys";

export default function useSignOutMutation() {
const router = useRouter();
const { onSignOut } = useContext(UserContext);
const queryClient = useQueryClient();

return useMutation({
mutationFn: postSignOut,
onSuccess: () => {
onSignOut();
router.push(Routes.LANDING);
queryClient.invalidateQueries({
queryKey: authKeys.authStatus.queryKey,
});
queryClient.invalidateQueries({
queryKey: userKeys.userInfo.queryKey,
});
},
meta: {
toastErrorMessage: "로그아웃을 다시 시도해주세요",
Expand Down
6 changes: 4 additions & 2 deletions src/features/user/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { fetcher } from "@/api/fetcher";
import { Response } from "@/api/types";
import { User } from "./types";

export const getUser = async () => {
const res = await fetcher.get<Response<{ user: User }>>("/profile");
export const getUser = async (cookies?: Record<string, string>) => {
const res = await fetcher.get<Response<{ user: User }>>("/profile", {
cookies,
});
return res.data;
};

Expand Down
5 changes: 5 additions & 0 deletions src/features/user/api/queries/queryKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createQueryKeys } from "@lukemorales/query-key-factory";

export const userKeys = createQueryKeys("user", {
userInfo: null,
});
14 changes: 14 additions & 0 deletions src/features/user/api/queries/useUserQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useQuery } from "@tanstack/react-query";
import { getUser } from "..";
import { userKeys } from "./queryKeys";

export default function useUserQuery(cookies?: Record<string, string>) {
return useQuery({
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useSuspensequery를 사용했을 때 문제가 있었는데 정확한 이유를 추후 찾아 수정할 필요있음

queryKey: userKeys.userInfo.queryKey,
queryFn: () => getUser(cookies),
select: (res) => res.data.user,
retry: 0,
gcTime: Infinity,
staleTime: Infinity,
});
}
1 change: 0 additions & 1 deletion src/features/user/components/desktop/UserControls.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import styled from "styled-components";
import UserDropdown from "./UserDropdown";

// export default function UserControls({ user }: { user: User }) {
export default function UserControls() {
return (
<StyledUserControls>
Expand Down
6 changes: 3 additions & 3 deletions src/features/user/components/desktop/UserDropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ import designSystem, { parseFontString } from "@/styles/designSystem";
import { Divider } from "@mui/material";
import Image from "next/image";
import Link from "next/link";
import { MouseEvent, useContext } from "react";
import { MouseEvent } from "react";
import styled from "styled-components";
import { UserContext } from "../../context/UserContext";
import useUserQuery from "../../api/queries/useUserQuery";
import UserProfileButton from "../UserProfileButton";

export default function UserDropdown() {
const { user } = useContext(UserContext);
const { data: user } = useUserQuery();
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

당장에 구현에는 설계한 방향으로 진행되고 있으나, tanstack query 캐싱이 아닌 브라우저의 http 캐싱으로 캐싱되어 이루어지고 있는 것 같음.

이 부분 다음 이슈 또는 추후에 개선이필요함


const { mutate: signOutMutate } = useSignOutMutation();

Expand Down
Loading