Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: SSR에 사용할 axios 인스턴스 생성 / 적용 #115

Merged
merged 6 commits into from
Oct 27, 2023
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
2 changes: 1 addition & 1 deletion next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const config = {
NEXT_PUBLIC_ENV: process.env.NEXT_PUBLIC_ENV,

// 필요할 때 끌어다 쓴 토큰
EXAMPLE_TOKEN: process.env.EXAMPLE_TOKEN,
SSR_TOKEN: process.env.SSR_TOKEN,

// NEXT-AUTH 설정에 필요한 값
NEXTAUTH_URL: process.env.NEXTAUTH_URL,
Expand Down
5 changes: 2 additions & 3 deletions src/components/common/dialog/Loading.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ const Loading = () => (
<div css={loadingContentsCSS}>
<Image
src="/spinnig-loading.gif"
width={100}
height={100}
width={50}
height={50}
alt="로딩"
priority
/>
Expand Down Expand Up @@ -42,6 +42,5 @@ const dialogBackdropCSS = css`
width: 100%;
height: 100%;
font-size: 1.25rem;
background: rgba(0, 0, 0, 0.2);
z-index: 1;
`;
2 changes: 1 addition & 1 deletion src/components/community/PostList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const boardListWrapperCSS = css`
display: flex;
flex-direction: column;
word-break: keep-all;
padding: 2rem;
padding: 2rem 0.5rem;
padding-top: 1.25rem;
width: 100%;
`;
20 changes: 5 additions & 15 deletions src/components/community/postList/Post.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,14 @@ const Post: FC<PostStates> = ({ characterId, post }) => (
</li>
</ul>
</FriendWrapper>
<div css={lineContainerCSS}>
<div css={lineCSS} />
</div>
<div css={lineCSS} />
</>
);

export default Post;

const postCSS = css`
padding: 0.2rem 0 0.2rem 0;
padding: 0.2rem 0 0.2rem 0.5rem;
width: 100%;
`;

Expand All @@ -64,6 +62,7 @@ const liCSS = css`
flex-direction: row;
align-items: center;
gap: 0.25rem;
padding-right: 0.3rem;
`;

const statusCSS = css`
Expand All @@ -72,19 +71,10 @@ const statusCSS = css`
color: ${color.black};
`;

const lineContainerCSS = css`
display: flex;
justify-content: center;
align-items: center;
width: 100%;
color: ${color.lightGray};
font-size: 0.875rem;
`;

const lineCSS = css`
display: block;
margin: 0.625rem;
height: 1px;
background: ${color.lightGray};
width: 100%;
background: ${color.lightGray};
margin: 0.2rem 0;
`;
86 changes: 44 additions & 42 deletions src/pages/chats/[character].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,64 +3,66 @@ import MessageInput from '@/components/chat/MessageInput';
import Header from '@/components/chat/Header';
import Main from '@/components/chat/Main';
import SEO from '@/components/common/head/SEO';
import { useEffect, useState } from 'react';
import { useEffect } from 'react';
import useChatStore from '@/store/chat';
import { useRouter } from 'next/router';
import { CharacterInfo } from '@/types/characterInfo';
import { findCharacterById } from '@/utils/api/character';
import Loading from '@/components/common/dialog/Loading';
import { ssrFindAllCharacters, ssrFindCharacterById } from '@/utils/api/character';
import { GetStaticPaths, GetStaticProps } from 'next';

const Character = () => {
const router = useRouter();
const { character: characterId } = router.query;
const [characterInfo, setCharacterInfo] = useState<CharacterInfo>();
const Character = ({ characterInfo }: { characterInfo: CharacterInfo }) => {
const { setChatInfo } = useChatStore();

useEffect(() => {
if (characterId && typeof characterId === 'string') {
findCharacterById(characterId)
.then((data) => {
setCharacterInfo(data);
setChatInfo(data.characterName, data.characterId);
})
.catch((error) => {
console.error('Error fetching post:', error);
});
}
}, [characterId]);
setChatInfo(characterInfo.characterName, characterInfo.characterId);
}, []);

return (
<>
<SEO title={characterInfo ? `대화 with ${characterInfo.characterName}` : '로딩 중'} />
<SEO title={`대화 with ${characterInfo.characterName}`} />
<section css={pageCSS}>
{characterInfo
? (
<>
<div>
<Header
characterId={characterInfo.characterId}
profileImageUrl={characterInfo.profileImageUrl}
characterName={characterInfo.characterName}
hashTag={characterInfo.hashTag}
/>
<Main
characterId={characterInfo.characterId}
characterName={characterInfo.characterName}
profileImageUrl={characterInfo.profileImageUrl}
/>
</div>
<MessageInput
characterId={Number(characterId)}
characterName={characterInfo.characterName}
/>
</>
) : <Loading />}
<div>
<Header
characterId={characterInfo.characterId}
profileImageUrl={characterInfo.profileImageUrl}
characterName={characterInfo.characterName}
hashTag={characterInfo.hashTag}
/>
<Main
characterId={characterInfo.characterId}
characterName={characterInfo.characterName}
profileImageUrl={characterInfo.profileImageUrl}
/>
</div>
<MessageInput
characterId={characterInfo.characterId}
characterName={characterInfo.characterName}
/>
</section>
</>
);
};
export default Character;

export const getStaticPaths: GetStaticPaths = async () => {
const characterIds = await ssrFindAllCharacters();

return {
paths: characterIds.map((data) => ({ params: { character: data.characterId.toString() } })),
fallback: 'blocking', // 존재하지 않는 경로의 경우, 서버에서 렌더링하도록 설정
};
};

export const getStaticProps: GetStaticProps = async (context) => {
const { character } = context.params!;

try {
const characterInfo = await ssrFindCharacterById(character as string);
return { props: { characterInfo } };
} catch (error) {
return { notFound: true };
}
};

const pageCSS = css`
min-height: 100vh;
display: flex;
Expand Down
2 changes: 1 addition & 1 deletion src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const Home = () => {
시작하기
</Button>
</Link>
<Link href="/chats/0">
<Link href="/chats/2">
<Button theme="white">
영준이와 대화하기
</Button>
Expand Down
6 changes: 3 additions & 3 deletions src/store/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ interface NewChatContentState {

export interface ChatState {
chatContents: ChatContentsState[],
chatInfo: { characterName: string, characterId: string } | null;
setChatInfo: (characterName: string, characterId: string) => void;
chatInfo: { characterName: string, characterId: number } | null;
setChatInfo: (characterName: string, characterId: number) => void;
clearChatContents: () => void;
initChatContents: (history: ChatContentsState[]) => void;
addChatContents: (newChat: NewChatContentState) => number;
Expand All @@ -22,7 +22,7 @@ export interface ChatState {
const useChatStore = create<ChatState>((set, get) => ({
chatContents: [],
chatInfo: null,
setChatInfo: (characterName: string, characterId: string) => set(() => ({
setChatInfo: (characterName: string, characterId: number) => set(() => ({
chatInfo: { characterId, characterName },
})),
clearChatContents: () => set(() => ({
Expand Down
3 changes: 2 additions & 1 deletion src/utils/api/accounts.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import defaultInstance from '@/utils/axiosInstance/defaultInstance';
import clientInstance from '@/utils/axiosInstance/clientInstance';
import ssrInstance from '@/utils/axiosInstance/ssrInstance';

interface Credentials {
email: string, password: string, provider: string
Expand Down Expand Up @@ -57,7 +58,7 @@ export const credentialsSignupAPI = async ({
provider: 'Credential',
};

const result = await defaultInstance.post('members/signup', sendSignupData);
const result = await ssrInstance.post('members/signup', sendSignupData);
return result.data;
};

Expand Down
16 changes: 14 additions & 2 deletions src/utils/api/character.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import { CharacterInfo } from '@/types/characterInfo';
import webServerInstance from '@/utils/axiosInstance/webServerInstance';
import ssrInstance from '@/utils/axiosInstance/ssrInstance';

export const findAllCharacters = async () => {
const result = await webServerInstance.get('/characters');
const result = await webServerInstance.get<CharacterInfo[]>('/characters');
return result.data;
};

export const findCharacterById = async (characterId: string) => {
const result = await webServerInstance.get(`/characters/${characterId}`);
const result = await webServerInstance.get<CharacterInfo>(`/characters/${characterId}`);
return result.data;
};

export const ssrFindAllCharacters = async () => {
const result = await ssrInstance.get<CharacterInfo[]>('/characters');
return result.data;
};

export const ssrFindCharacterById = async (characterId: string) => {
const result = await ssrInstance.get<CharacterInfo>(`/characters/${characterId}`);
return result.data;
};
29 changes: 29 additions & 0 deletions src/utils/axiosInstance/ssrInstance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import axios, { AxiosError } from 'axios';

const ssrInstance = axios.create({
baseURL: `${process.env.NEXT_PUBLIC_SERVER_URL || 'http://localhost:8080/'}api/`,
});

ssrInstance.interceptors.response.use((response) => response, (error: AxiosError) => {
console.error('ERROR', error.toJSON());
if (error.response && error.response.status === 401) {
console.error('ERROR', error.toJSON());
}
return Promise.reject(error);
});

ssrInstance.interceptors.request.use(
async (config) => {
const token = process.env.SSR_TOKEN;

if (token) {
// eslint-disable-next-line no-param-reassign
config.headers.Authorization = `Bearer ${token}`;
}

return config;
},
(error) => Promise.reject(error),
);

export default ssrInstance;
Loading