From 4e8b2fce3a86c4922eb127ed25af9dd55bbd712e Mon Sep 17 00:00:00 2001 From: JunYoungKr Date: Fri, 26 Jul 2024 20:29:58 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20[23]=20=EB=A7=88=EC=9D=B4=ED=8E=98?= =?UTF-8?q?=EC=9D=B4=EC=A7=80=20=EB=8D=B0=ED=83=91=20=EB=94=94=EC=9E=90?= =?UTF-8?q?=EC=9D=B8=20=EC=88=98=EC=A0=95=20=EB=B0=8F=20api=20=EB=B6=84?= =?UTF-8?q?=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/pages/main/mainPage/MainPage.js | 182 ++------------------ src/pages/main/mainPage/MainPage.module.css | 53 ++++-- src/pages/main/mainPage/api.js | 123 +++++++++++++ src/pages/myPage/mypage/api.js | 32 ++-- src/pages/study/studyList/StudyListPost.js | 6 +- src/pages/study/studyList/api.js | 1 + src/pages/study/studyPostDetail/api.js | 102 +++-------- 7 files changed, 217 insertions(+), 282 deletions(-) create mode 100644 src/pages/main/mainPage/api.js diff --git a/src/pages/main/mainPage/MainPage.js b/src/pages/main/mainPage/MainPage.js index 24a304ba..50c57531 100644 --- a/src/pages/main/mainPage/MainPage.js +++ b/src/pages/main/mainPage/MainPage.js @@ -1,5 +1,5 @@ import { useContext, useEffect, useState } from 'react'; -import { Link, useNavigate } from 'react-router-dom'; +import { useNavigate } from 'react-router-dom'; import { MyContext } from '../../../App'; import MainBuddy from './MainBuddy'; @@ -16,147 +16,20 @@ import ready from '../../../assets/image/ready.png'; import style from './MainPage.module.css'; import useStudyInfoStore from '../../study/useStudyInfoStore'; +import { BuddyHandler, HonbobHandler } from './api'; // Import API functions + const images = [honbobUse, buddyUse, peerUse]; const MainPage = () => { const navigate = useNavigate(); - const refreshToken = localStorage.getItem('refreshToken'); - const accessToken = localStorage.getItem('accessToken'); const { setBuddyCount } = useContext(MyContext); - - // 동물상 미팅 페이지 이동 - const goResult = () => { - navigate('/fest/AnimalApply'); - }; - - // 동물상 결과 확인 - const goAnimalResult = () => { - navigate('/fest/animalcheck'); - }; - - // 버디 상태 확인 - const BuddyHandler = async () => { - if (refreshToken === null || accessToken === null) { - alert('로그인 후 이용 가능한 서비스입니다!'); - navigate('/login'); - } else { - try { - const response = await fetch( - process.env.REACT_APP_BACK_SERVER + '/buddy/check-matching-status', - { - method: 'GET', - headers: { - Authorization: `Bearer ${localStorage.getItem('accessToken')}`, - 'Refresh-Token': localStorage.getItem('refreshToken'), - }, - } - ); - const data = await response.json(); - // console.log(data.data); - - if (data.data !== null) setBuddyCount(data.data.matchingCompletedCount); - else setBuddyCount(0); - - //상태 관리 - if (data.data === null) { - navigate('/buddy/start1'); - } else { - statusHandler(data.data.status, data.data.matchingCompletedCount); - } - } catch (error) { - alert('에러가 발생했습니다.'); - console.log(error.message); - } - } - }; - - //버디 - 상태에따른 처리 - const statusHandler = (status, count) => { - //취소, 거절 패널티 해제 - if (status === 'CANCEL' || status === 'REACTIVATE') { - if (count > 0) { - navigate('/buddy/success'); - } else { - navigate('/buddy/start1'); - } - // 거절 당함 - } else if (status === 'DENIED') { - alert('상대방이 거절했습니다. 다시 신청해 주세요.'); - if (count > 0) { - navigate('/buddy/success'); - } else { - navigate('/buddy/start1'); - } - //매칭 최종 완료 - } else if (status === 'MATCHING_COMPLETED') { - alert('매칭에 성공했습니다. 정보를 확인해주세요!'); - navigate('/buddy/success'); - //매칭 수락 - } else if (status === 'ACCEPT') { - alert('신청 수락을 했습니다. 상대방이 수락할때까지 기다려 주세요.'); - //매칭 거절 - } else if (status === 'REJECT') { - alert( - '거절 패널티 1시간이 부과되었습니다. 1시간 이후에 다시 신청해 주세요.' - ); - //매칭 중 - } else if (status === 'IN_PROGRESS') { - alert('매칭중입니다!'); - navigate('/buddy/waiting'); - //매칭 완료 - } else if (status === 'FOUND_BUDDY') { - alert('버디를 찾았습니다!'); - navigate('/buddy/accept'); - } - }; - - //혼밥 상태 확인 - const HonbobHandler = async () => { - if (refreshToken === null || accessToken === null) { - alert('로그인 후 이용 가능한 서비스입니다!'); - navigate('/login'); - } else { - try { - const response = await fetch( - process.env.REACT_APP_BACK_SERVER + '/honbab/check-matching-status', - { - method: 'GET', - headers: { - Authorization: `Bearer ${localStorage.getItem('accessToken')}`, - 'Refresh-Token': localStorage.getItem('refreshToken'), - }, - } - ); - if (!response.ok) { - throw new Error('Network response was not ok'); // 응답 상태가 좋지 않을 경우 에러를 발생시킴 - } - const data = await response.json(); // 주석 해제하여 JSON 응답을 파싱 - - if (data.data === null || data.data.status === 'CANCEL') { - navigate('/honbob/start1'); - } else if ( - data.data.status === 'TIME_OUT' || - data.data.status === 'EXPIRED' - ) { - navigate('/honbob/start1'); - } else if (data.data.status === 'IN_PROGRESS') { - alert('매칭 중입니다!'); - navigate('/honbob/waiting'); - } else if (data.data.status === 'MATCHING_COMPLETED') { - alert('매칭에 성공했습니다!'); - navigate('/honbob/success'); - } - } catch (error) { - console.error('에러 체크:', error); - alert('매칭 체크 실패!'); - } - } - }; - //studyType설정 const { studyType, setStudyType } = useStudyInfoStore(); + // StudyHandler function to set study type and navigate const StudyHandler = () => { setStudyType('lecture'); + const refreshToken = localStorage.getItem('refreshToken'); + const accessToken = localStorage.getItem('accessToken'); if (refreshToken === null || accessToken === null) { alert('로그인 후 이용 가능한 서비스입니다!'); navigate('/login'); @@ -164,9 +37,6 @@ const MainPage = () => { if (studyType === 'lecture') navigate('/study'); } }; - const reportUserHandler = () => { - alert('너 신고'); - }; const [currentImageIndex, setCurrentImageIndex] = useState(0); const [slideIn, setSlideIn] = useState(true); @@ -229,7 +99,7 @@ const MainPage = () => { className={style.useImg} src={images[currentImageIndex]} onClick={() => onImageClick(currentImageIndex)} - > + />
{ + onClick={() => BuddyHandler(navigate, setBuddyCount)} + /> + onClick={() => HonbobHandler(navigate)} + />
{/* 세종 스터디 버튼 임시로 숨겨둠 - 축제 때문에 */}
-

- 세종스터디 -

-

인생 팀원 구하기

+

세종스터디

+

+ 인생 팀원 구하기 +

- {/* - */}
- {/* */}
- {/* */} ); }; diff --git a/src/pages/main/mainPage/MainPage.module.css b/src/pages/main/mainPage/MainPage.module.css index bf911768..5a532de8 100644 --- a/src/pages/main/mainPage/MainPage.module.css +++ b/src/pages/main/mainPage/MainPage.module.css @@ -50,7 +50,7 @@ .festButton { display: flex; justify-content: center; - align-items: flex-end; + /* align-items: center; */ gap: 7px; background-color: white; height: 204px; @@ -58,23 +58,46 @@ border: 1px solid #e5e5e5; border-radius: 16px; margin-top: 2vh; + flex-direction: column; } - .festButton { - width: 351px; - height: 204px; - /* background-image: url('../../../assets/image/Festival.png'); */ - background-repeat: no-repeat; - background-position: center; - background-size: cover; + + .studyText { + display: flex; + flex-direction: row; + align-items: baseline; + margin-left: 16px; + } + + .title { + font-family: 'jalnan'; + margin: 16px 4px 4px 0px; + } + + .studyContainer { display: flex; justify-content: center; - align-items: center; - margin-top: 10px; - border: 1px solid #e5e5e5; - border-radius: 15px; gap: 7px; } + .school { + width: 152px; + height: 136px; + background-image: url('../../../assets/image/school.png'); + background-position: center; + background-repeat: no-repeat; + background-size: contain; + background-color: white; + } + + .except { + width: 152px; + height: 136px; + background-image: url('../../../assets/image/except.png'); + background-position: center; + background-repeat: no-repeat; + background-size: contain; + background-color: white; + } .festButton2 { margin-top: 144px; width: 152px; @@ -307,6 +330,12 @@ align-items: baseline; margin-left: 16px; } + + .title { + font-family: 'jalnan'; + margin: 16px 4px 12px 0px; + } + .studyContainer { display: flex; justify-content: center; diff --git a/src/pages/main/mainPage/api.js b/src/pages/main/mainPage/api.js new file mode 100644 index 00000000..854b42c3 --- /dev/null +++ b/src/pages/main/mainPage/api.js @@ -0,0 +1,123 @@ +// api.js + +// Buddy 상태 확인 +export const BuddyHandler = async (navigate, setBuddyCount) => { + const refreshToken = localStorage.getItem('refreshToken'); + const accessToken = localStorage.getItem('accessToken'); + + if (refreshToken === null || accessToken === null) { + alert('로그인 후 이용 가능한 서비스입니다!'); + navigate('/login'); + } else { + try { + const response = await fetch( + process.env.REACT_APP_BACK_SERVER + '/buddy/check-matching-status', + { + method: 'GET', + headers: { + Authorization: `Bearer ${accessToken}`, + 'Refresh-Token': refreshToken, + }, + } + ); + const data = await response.json(); + + if (data.data !== null) setBuddyCount(data.data.matchingCompletedCount); + else setBuddyCount(0); + + statusHandler( + data.data.status, + data.data.matchingCompletedCount, + navigate + ); + } catch (error) { + alert('에러가 발생했습니다.'); + console.log(error.message); + } + } +}; + +const statusHandler = (status, count, navigate) => { + switch (status) { + case 'CANCEL': + case 'REACTIVATE': + navigate(count > 0 ? '/buddy/success' : '/buddy/start1'); + break; + case 'DENIED': + alert('상대방이 거절했습니다. 다시 신청해 주세요.'); + navigate(count > 0 ? '/buddy/success' : '/buddy/start1'); + break; + case 'MATCHING_COMPLETED': + alert('매칭에 성공했습니다. 정보를 확인해주세요!'); + navigate('/buddy/success'); + break; + case 'ACCEPT': + alert('신청 수락을 했습니다. 상대방이 수락할때까지 기다려 주세요.'); + break; + case 'REJECT': + alert( + '거절 패널티 1시간이 부과되었습니다. 1시간 이후에 다시 신청해 주세요.' + ); + break; + case 'IN_PROGRESS': + alert('매칭중입니다!'); + navigate('/buddy/waiting'); + break; + case 'FOUND_BUDDY': + alert('버디를 찾았습니다!'); + navigate('/buddy/accept'); + break; + default: + break; + } +}; + +export const HonbobHandler = async navigate => { + const refreshToken = localStorage.getItem('refreshToken'); + const accessToken = localStorage.getItem('accessToken'); + + if (refreshToken === null || accessToken === null) { + alert('로그인 후 이용 가능한 서비스입니다!'); + navigate('/login'); + } else { + try { + const response = await fetch( + process.env.REACT_APP_BACK_SERVER + '/honbab/check-matching-status', + { + method: 'GET', + headers: { + Authorization: `Bearer ${accessToken}`, + 'Refresh-Token': refreshToken, + }, + } + ); + + if (!response.ok) { + throw new Error('Network response was not ok'); + } + + const data = await response.json(); + + switch (data.data.status) { + case 'CANCEL': + case 'TIME_OUT': + case 'EXPIRED': + navigate('/honbob/start1'); + break; + case 'IN_PROGRESS': + alert('매칭 중입니다!'); + navigate('/honbob/waiting'); + break; + case 'MATCHING_COMPLETED': + alert('매칭에 성공했습니다!'); + navigate('/honbob/success'); + break; + default: + break; + } + } catch (error) { + console.error('에러 체크:', error); + alert('매칭 체크 실패!'); + } + } +}; diff --git a/src/pages/myPage/mypage/api.js b/src/pages/myPage/mypage/api.js index 3fbb6e6f..495b018b 100644 --- a/src/pages/myPage/mypage/api.js +++ b/src/pages/myPage/mypage/api.js @@ -1,5 +1,4 @@ import axios from 'axios'; -import useScrapStore from './useScrapStore'; export const fetchScraps = async () => { const accessToken = localStorage.getItem('accessToken'); @@ -8,22 +7,21 @@ export const fetchScraps = async () => { if (!accessToken || !refreshToken) { throw new Error('Tokens not found in local storage.'); } - const response = await axios.get( - `${process.env.REACT_APP_BACK_SERVER}/scraps/all`, - { - params: { - studyType: 'LECTURE', - page: 0, - }, - headers: { - Authorization: `Bearer ${accessToken}`, - 'Refresh-token': refreshToken, - 'Content-Type': 'application/json', - }, - withCredentials: true, - } - ); + const response = await axios.get( + `${process.env.REACT_APP_BACK_SERVER}/scraps/all`, + { + params: { + studyType: 'LECTURE', + page: 0, + }, + headers: { + Authorization: `Bearer ${accessToken}`, + 'Refresh-token': refreshToken, + 'Content-Type': 'application/json', + }, + withCredentials: true, + } + ); console.log(response.data.data); return response.data.data; }; - diff --git a/src/pages/study/studyList/StudyListPost.js b/src/pages/study/studyList/StudyListPost.js index aec5adec..2b85b0b8 100644 --- a/src/pages/study/studyList/StudyListPost.js +++ b/src/pages/study/studyList/StudyListPost.js @@ -34,12 +34,8 @@ const StudyListPost = ({ post }) => { - 0 + {post.scrapCount} - {/* - - 0 - */} ); diff --git a/src/pages/study/studyList/api.js b/src/pages/study/studyList/api.js index 35c1cd1f..178ad28f 100644 --- a/src/pages/study/studyList/api.js +++ b/src/pages/study/studyList/api.js @@ -26,5 +26,6 @@ export const fetchPosts = async () => { } ); console.log(response.data.data); + console.log(response.data.data.content[0].id); return response.data.data.content; }; diff --git a/src/pages/study/studyPostDetail/api.js b/src/pages/study/studyPostDetail/api.js index e57f0536..2f294eb1 100644 --- a/src/pages/study/studyPostDetail/api.js +++ b/src/pages/study/studyPostDetail/api.js @@ -1,7 +1,6 @@ -// src/api/study.js import axios from 'axios'; -export const fetchStudyData = async studyId => { +const getAuthHeaders = () => { const accessToken = localStorage.getItem('accessToken'); const refreshToken = localStorage.getItem('refreshToken'); @@ -10,135 +9,76 @@ export const fetchStudyData = async studyId => { throw new Error('토큰이 없음!'); } + return { + 'Content-Type': 'application/json', + Authorization: `Bearer ${accessToken}`, + 'Refresh-token': `${refreshToken}`, + }; +}; + +export const fetchStudyData = async studyId => { const response = await axios.get( `${process.env.REACT_APP_BACK_SERVER}/study/post/${studyId}`, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${accessToken}`, - 'Refresh-token': `${refreshToken}`, - }, + headers: getAuthHeaders(), } ); - console.log(response.data); return response.data; }; export const applyForStudy = async studyId => { - const accessToken = localStorage.getItem('accessToken'); - const refreshToken = localStorage.getItem('refreshToken'); - - if (!accessToken || !refreshToken) { - alert('재로그인 해야합니다!'); - throw new Error('토큰이 없음!'); - } - const response = await axios.post( `${process.env.REACT_APP_BACK_SERVER}/study/relations`, { studyId: parseInt(studyId) }, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${accessToken}`, - 'Refresh-token': `${refreshToken}`, - }, + headers: getAuthHeaders(), } ); - console.log(response.data); return response; }; -// 스터디 지원 취소 export const cancelStudyApplication = async studyId => { - const accessToken = localStorage.getItem('accessToken'); - const refreshToken = localStorage.getItem('refreshToken'); - - if (!accessToken || !refreshToken) { - alert('재로그인 해야합니다!'); - throw new Error('토큰이 없음!'); - } - const response = await axios.delete( `${process.env.REACT_APP_BACK_SERVER}/study/relations/${studyId}`, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${accessToken}`, - 'Refresh-token': `${refreshToken}`, - }, + headers: getAuthHeaders(), } ); - console.log(response.data); return response; }; -// 스터디 스크랩 함수 export const toggleScrap = async (studyId, isScrapped) => { - const accessToken = localStorage.getItem('accessToken'); - const refreshToken = localStorage.getItem('refreshToken'); const scrapId = localStorage.getItem(`scrapId_${studyId}`); - if (!accessToken || !refreshToken) { - alert('재로그인 해야합니다!'); - throw new Error('토큰이 없음!'); - } - if (isScrapped) { if (!scrapId) { throw new Error('스크랩 ID가 없음!'); } - // DELETE 요청 - const url = `${process.env.REACT_APP_BACK_SERVER}/scraps/${scrapId}`; - const response = await axios.delete(url, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${accessToken}`, - 'Refresh-token': refreshToken, - }, - }); - // console.log(response.data); + const response = await axios.delete( + `${process.env.REACT_APP_BACK_SERVER}/scraps/${scrapId}`, + { + headers: getAuthHeaders(), + } + ); return response; } else { - // POST 요청 - const url = `${process.env.REACT_APP_BACK_SERVER}/scraps/study/${studyId}`; - const scrapId = localStorage.getItem(`scrapId_${studyId}`); const response = await axios.post( - url, + `${process.env.REACT_APP_BACK_SERVER}/scraps/study/${studyId}`, {}, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${accessToken}`, - 'Refresh-token': refreshToken, - }, + headers: getAuthHeaders(), } ); - // console.log(response.data); return response; } }; -// 단건 게시물 별 스크랩 수 조회 export const fetchScrapCount = async studyId => { - const accessToken = localStorage.getItem('accessToken'); - const refreshToken = localStorage.getItem('refreshToken'); - - if (!accessToken || !refreshToken) { - alert('재로그인 해야합니다!'); - throw new Error('토큰이 없음!'); - } - const response = await axios.get( `${process.env.REACT_APP_BACK_SERVER}/scraps/study/${studyId}`, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${accessToken}`, - 'Refresh-token': `${refreshToken}`, - }, + headers: getAuthHeaders(), } ); - - // console.log(response.data); return response.data; };