Skip to content

Commit

Permalink
Merge pull request #22 from team-Ollie/main
Browse files Browse the repository at this point in the history
feat: 마이페이지, 캘린더 api 연결
  • Loading branch information
leejin-rho authored Jun 27, 2024
2 parents 0396c64 + 38e3be2 commit d70117f
Show file tree
Hide file tree
Showing 45 changed files with 2,076 additions and 234 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/nextjs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ on:
push:
branches: ["deploy"]
pull_request:
branches: ["deploy"]
branches: ["deploy", "main"]

# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
Expand Down
34 changes: 34 additions & 0 deletions apis/auth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import client from "./client";

export const SignIn = async (userData: {
loginId: string;
password: string;
}) => {
try {
const response = await client.post(
"/users/login",
{
loginId: userData.loginId,
password: userData.password,
},
{
headers: {
"Content-Type": "application/json",
},
},
);
return response.data;
} catch (error) {
if (error.response) {
// 200 이외
console.error("서버 응답 오류:", error.response.data);
} else if (error.request) {
// 요청이 전송되었으나 응답을 받지 못한 경우
console.error("응답 없음:", error.request);
} else {
// 요청을 설정하는 도중에 발생한 오류
console.error("요청 설정 오류:", error.message);
}
throw error;
}
};
53 changes: 53 additions & 0 deletions apis/calendar.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import client, { ResponseBody } from "./client";

interface GetMonthCalendarResponse extends ResponseBody {
result: MonthCalendarProps[];
}

export interface MonthCalendarProps {
programIdx: number;
name: string;
openDate: {
year: number;
month: number;
day: number;
};
dueDate: {
year: number;
month: number;
day: number;
};
}

type CalendarDate = {
year: number;
month: number;
day: number;
};

interface GetProgramDetailBody {
programIdx: number;
name: string;
openDate: CalendarDate;
dueDate: CalendarDate;
location: string;
host: string;
schedule: string;
description: string;
}

// 챌린지 월별 조회
export const getMonthCalendar = async (): Promise<GetMonthCalendarResponse> => {
const response = await client.get("/programs");
// console.log("calenderData", response.data.result);
return response.data.result;
};

export const getProgramDetail = async (
programIdx: number,
): Promise<GetProgramDetailBody> => {
// const response = await client.get(`/programs/${programIdx}`);
const response = await client.get(`/programs/2`);
// console.log("calenderDetail", response.data.result);
return response.data.result;
};
21 changes: 21 additions & 0 deletions apis/challenge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import client, { ResponseBody } from "./client";

interface GetMyChallengeListResponse extends ResponseBody {
result: Challenge[];
}

export interface Challenge {
challengeIdx: number;
name: string;
participantsNum: number;
location: string;
schedule: string;
attendanceRate: number;
totalAttendanceRate: number;
}
async function getMyChallengeList(): Promise<GetMyChallengeListResponse> {
const { data } = await client.get(`/challenges`);
return data;
}

export { getMyChallengeList };
44 changes: 44 additions & 0 deletions apis/client.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,52 @@
import axios from "axios";

interface ResponseBody {
isSuccess: boolean;
code: number;
message: string;
}

export const setTokenFromLocalStorage = (access_token: string) => {
localStorage.setItem("access_token", access_token);
};

const getTokenFromLocalStorage = () => {
const accessToken = localStorage.getItem("access_token");
if (!accessToken) {
return null;
}
return accessToken;
};

const client = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
withCredentials: true,
headers: {
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Credentials": "true",
},
validateStatus: (status) => {
return status < 300;
},
});

client.interceptors.request.use(
async (config) => {
if (typeof document !== "undefined") {
const loginUrl = "/users/login";
if (!config.url.includes(loginUrl)) {
const token = getTokenFromLocalStorage();
if (token) {
config.headers.set("Authorization", `Bearer ${token}`);
}
}
}
return config;
},
(error) => {
return Promise.reject(error);
},
);

export default client;
export type { ResponseBody };
26 changes: 26 additions & 0 deletions apis/hooks/calendar.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useQuery } from "@tanstack/react-query";
import { getMonthCalendar, getProgramDetail } from "../calendar";

const useGetMonthCalendar = () => {
const { data } = useQuery({
queryKey: ["getMonthCalendar"],
queryFn: getMonthCalendar,
});
// console.log("isLoading", isLoading);
console.log("Query Data", data);
return { data };
};

export { useGetMonthCalendar };

// const useGetProgramDetail = () => {
// const { data } = useQuery({
// queryKey: ["getProgramDetail"],
// queryFn: getProgramDetail,
// });
// // console.log("isLoading", isLoading);
// console.log("Query Data", data);
// return { data };
// };

// export { useGetProgramDetail };
13 changes: 13 additions & 0 deletions apis/hooks/challenge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { getMyChallengeList } from "../challenge";
import { useQuery } from "@tanstack/react-query";

function useGetMyChallengeList() {
const { data } = useQuery({
queryKey: ["getMyChallengeList"],
queryFn: getMyChallengeList,
});

return { data };
}

export { useGetMyChallengeList };
103 changes: 103 additions & 0 deletions apis/hooks/mypage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { useQuery, useMutation } from "@tanstack/react-query";
import {
getMyInfo,
patchLogout,
patchNicknameChange,
patchPasswordChange,
patchQuitAccount,
postNicknameCheck,
} from "../mypage";
import { useRouter } from "next/router";
import { InputError } from "@/pages/mypage/password";

function useGetMyInfo() {
const { data } = useQuery({
queryKey: ["getMyInfo"],
queryFn: getMyInfo,
});

return { data };
}

function usePatchLogout() {
const router = useRouter();
const { mutate } = useMutation({
mutationKey: ["patchLogout"],
mutationFn: patchLogout,
onSuccess: () => {
localStorage.removeItem("access_token");
router.push("/main");
},
onError: () => router.push("/404"),
});

return { mutate };
}

function usePatchQuitAccount(
setPwError: React.Dispatch<React.SetStateAction<InputError>>,
) {
const router = useRouter();
const { mutate } = useMutation({
mutationKey: ["patchQuitAccount"],
mutationFn: (password: string) => patchQuitAccount(password),
onSuccess: () => {
localStorage.removeItem("access_token");
router.push("/main");
},
onError: () =>
setPwError({ status: true, text: "비밀번호가 올바르지 않습니다." }),
});

return { mutate };
}

function usePatchPasswordChange() {
const router = useRouter();
const { mutate } = useMutation({
mutationKey: ["patchPasswordChange"],
mutationFn: (body: { password: string; newPassword: string }) =>
patchPasswordChange(body),
onSuccess: () => router.push("/mypage/password/success"),
onError: () => router.push("/404"),
});

return { mutate };
}

function usePatchNicknameChange(nickname: string) {
const router = useRouter();
const { mutate } = useMutation({
mutationKey: ["postNicknameCheck", nickname],
mutationFn: () => patchNicknameChange(nickname),
onSuccess: () => router.push("/mypage/nickname/success"),
onError: () => router.push("/404"),
});

return { mutate };
}

function usePostNicknameCheck(
nickname: string,
setNameError: React.Dispatch<React.SetStateAction<InputError>>,
) {
const { mutate } = useMutation({
mutationKey: ["postNicknameCheck", nickname],
mutationFn: () => postNicknameCheck(nickname),
onSuccess: () => setNameError({ status: false, text: "" }),
onError: () => {
setNameError({ status: true, text: "이미 사용 중인 닉네임입니다." });
},
});

return { mutate };
}

export {
useGetMyInfo,
usePatchLogout,
usePatchQuitAccount,
usePatchPasswordChange,
usePatchNicknameChange,
usePostNicknameCheck,
};
71 changes: 71 additions & 0 deletions apis/mypage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import client, { ResponseBody } from "./client";

interface GetMyInfoResponse extends ResponseBody {
result: {
nickname: string;
level: number;
loginId: string;
isAdmin: boolean;
};
}

interface PatchResponse {
isSuccess: boolean;
message: string;
}

interface QuitAccountResponseBody {
timestamp: string;
status: number;
error: string;
code: string;
message: string;
}

async function getMyInfo(): Promise<GetMyInfoResponse> {
const { data } = await client.get(`/users/myPage`);
return data;
}

async function patchLogout(): Promise<PatchResponse> {
const { data } = await client.patch(`/users/logout`);
return data;
}

async function patchQuitAccount(
password: string,
): Promise<QuitAccountResponseBody> {
const { data } = await client.patch(`/users/signout`, { password });
return data;
}

async function patchPasswordChange(body: {
password: string;
newPassword: string;
}): Promise<PatchResponse> {
const { data } = await client.patch(`/users/editPassword`, body);
return data;
}

async function patchNicknameChange(
nickname: string,
): Promise<QuitAccountResponseBody> {
const { data } = await client.patch(`/users/editNickname`, { nickname });
return data;
}

async function postNicknameCheck(
nickname: string,
): Promise<QuitAccountResponseBody> {
const { data } = await client.post(`/users/nickname`, { nickname });
return data;
}

export {
getMyInfo,
patchLogout,
patchQuitAccount,
patchPasswordChange,
patchNicknameChange,
postNicknameCheck,
};
Loading

0 comments on commit d70117f

Please sign in to comment.