Skip to content

Commit

Permalink
refactor : SSR fetch함수 분리
Browse files Browse the repository at this point in the history
  • Loading branch information
teawon committed Oct 15, 2023
1 parent 03eca00 commit d2ec9e3
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 37 deletions.
8 changes: 4 additions & 4 deletions Mindspace_front_next/app/api/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { baseFetch } from "./baseFetch";
import { csrFetch } from "./utils/csrFetch";
import {
NicknameResponse,
SignInResponse,
Expand All @@ -18,7 +18,7 @@ export const createUser = async ({
password: password,
});

await baseFetch(endpoint, {
await csrFetch(endpoint, {
method: "POST",
body: body,
});
Expand All @@ -36,7 +36,7 @@ export const getAccessToken = async ({
password: password,
});

const response = await baseFetch<SignInResponse>(endpoint, {
const response = await csrFetch<SignInResponse>(endpoint, {
method: "POST",
body: body,
});
Expand All @@ -48,7 +48,7 @@ export const getAccessToken = async ({
export const getUserNickname = async (): Promise<string> => {
const endpoint = "user/nickname";

const response = await baseFetch<NicknameResponse>(endpoint, {
const response = await csrFetch<NicknameResponse>(endpoint, {
method: "GET",
});

Expand Down
4 changes: 2 additions & 2 deletions Mindspace_front_next/app/api/node.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { baseFetch } from "./baseFetch";
import { csrFetch } from "./utils/csrFetch";
import { GraphData } from "@/constants/types";

export const getNodeList = async (): Promise<GraphData> => {
const endpoint = "node/check";

const response = await baseFetch<GraphData>(endpoint, {
const response = await csrFetch<GraphData>(endpoint, {
method: "GET",
});

Expand Down
17 changes: 17 additions & 0 deletions Mindspace_front_next/app/api/nodeServer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { ssrFetch } from "./utils/ssrFetch";
import { GraphData } from "@/constants/types";

export const getNodeListSSR = async (): Promise<GraphData> => {
const endpoint = "node/check";

const response = await ssrFetch<GraphData>(endpoint, {
method: "GET",
});

const nodeList = {
nodes: response.nodes,
links: response.links,
};

return nodeList;
};
Original file line number Diff line number Diff line change
@@ -1,37 +1,10 @@
import Cookies from "js-cookie";

const VERSION = "api/v1/";
const BASEURL = `${process.env.NEXT_PUBLIC_API_URL}${VERSION}`;

const defaultHeaders = {
"Content-Type": "application/json",
};

export async function baseFetch<T = any>(
endpoint: string,
options?: RequestInit,
) {
const accessToken = Cookies.get("accessToken");

const authHeader: Record<string, string> = {};
if (accessToken) {
authHeader.Authorization = `${accessToken}`;
// TODO 향후 Bearer(혹은 기타 토큰타입) 를 붙여 토큰정보를 보낼 것
}
const combinedHeaders = {
...defaultHeaders,
...authHeader,
...options?.headers,
};

const response = await fetch(`${BASEURL}${endpoint}`, {
...options,
headers: new Headers(combinedHeaders),
});

return handleResponse<T>(response);
}

async function handleResponse<T>(response: Response): Promise<T> {
const contentType = response.headers.get("Content-Type") || "";
const isJson = contentType.includes("application/json");
Expand All @@ -46,3 +19,20 @@ async function handleResponse<T>(response: Response): Promise<T> {

return data as T;
}

export const baseFetch = async <T = any>(
endpoint: string,
headers: HeadersInit,
options?: RequestInit,
): Promise<T> => {
const response = await fetch(`${BASEURL}${endpoint}`, {
...options,
headers: new Headers({
...defaultHeaders,
...headers,
...options?.headers,
}),
});

return handleResponse<T>(response);
};
16 changes: 16 additions & 0 deletions Mindspace_front_next/app/api/utils/csrFetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Cookies from "js-cookie";
import { baseFetch } from "./baseFetch";

export const csrFetch = async <T = any>(
endpoint: string,
options?: RequestInit,
): Promise<T> => {
const accessToken = Cookies.get("accessToken");
const authHeader: Record<string, string> = {};

if (accessToken) {
authHeader.Authorization = `${accessToken}`;
}

return baseFetch<T>(endpoint, authHeader, options);
};
18 changes: 18 additions & 0 deletions Mindspace_front_next/app/api/utils/ssrFetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { cookies } from "next/headers";
import { baseFetch } from "./baseFetch";

export const ssrFetch = async <T = any>(
endpoint: string,
options?: RequestInit,
): Promise<T> => {
const nextCookies = cookies();
const accessToken = nextCookies.get("accessToken")?.value;

const authHeader: Record<string, string> = {};

if (accessToken) {
authHeader.Authorization = `${accessToken}`;
}

return baseFetch<T>(endpoint, authHeader, options);
};
4 changes: 2 additions & 2 deletions Mindspace_front_next/app/map/hydratedNode.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { dehydrate } from "@tanstack/react-query";
import getQueryClient from "@/getQueryClient";
import { getNodeList } from "@/api/node";
import { getNodeListSSR } from "@/api/nodeServer";
import { NODE_QUERIES } from "@/constants/queryKeys";
import MapPage from "./map";
import HydrateOnClient from "@/hydrateOnClient";

export default async function HydratedNode() {
const queryClient = getQueryClient();
await queryClient.prefetchQuery([NODE_QUERIES.LIST], getNodeList);
await queryClient.prefetchQuery([NODE_QUERIES.LIST], getNodeListSSR);

const dehydratedState = dehydrate(queryClient);

Expand Down
3 changes: 1 addition & 2 deletions Mindspace_front_next/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ export const config = {
export function middleware(request: NextRequest) {
const token = getTokenFromCookies(request);
const currentPath = request.nextUrl.pathname;
const url = request.nextUrl.clone();

if (!token && ROUTES.AUTH_REQUIRED.includes(currentPath)) {
const url = request.nextUrl.clone();
url.pathname = "/signin";
return NextResponse.redirect(url);
}

if (token && ROUTES.NON_AUTH_ACCESSIBLE.includes(currentPath)) {
const url = request.nextUrl.clone();
url.pathname = "/";
return NextResponse.redirect(url);
}
Expand Down

0 comments on commit d2ec9e3

Please sign in to comment.