Skip to content

Commit

Permalink
Merge pull request #51 from naya-h2/feat/API
Browse files Browse the repository at this point in the history
✨ feat: 공통 api 함수 구현 완료
  • Loading branch information
Nico1eKim authored Feb 3, 2024
2 parents b733b33 + f44f364 commit ba6b74d
Show file tree
Hide file tree
Showing 4 changed files with 256 additions and 5 deletions.
93 changes: 93 additions & 0 deletions app/_api/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
export class Api {
private baseUrl;
private queryString;
private accessToken;

constructor(token?: string) {
this.baseUrl = "";
this.queryString = "";
this.accessToken = token;
}

private makeQueryString(querys: QueryType) {
this.queryString = "?";
if (querys) {
const queryKeyList = Object.keys(querys);
queryKeyList.forEach((query, idx) => {
this.queryString += `${query}=${querys[query as keyof QueryType]}`;
if (idx !== queryKeyList.length - 1) {
this.queryString += "&";
}
});
}
}

async get(endPoint: GetEndPoint, querys?: QueryType) {
this.baseUrl = "/api" + endPoint;
if (querys) {
this.makeQueryString(querys);
}
const res = await fetch(querys ? this.baseUrl + this.queryString : this.baseUrl, {
headers: {
Authorization: `Bearer ${this.accessToken}`,
},
});
return await res.json();
}

async post<T>(endPoint: PostEndPoint, body: T, querys?: QueryType) {
this.baseUrl = "/api" + endPoint;
if (querys) {
this.makeQueryString(querys);
}
const res = await fetch(querys ? this.baseUrl + this.queryString : this.baseUrl, {
method: "POST",
body: endPoint === "/file/upload" ? (body as FormData) : JSON.stringify(body),
headers: {
...(endPoint === "/file/upload" ? {} : { "Content-Type": "application/json" }),
Authorization: `Bearer ${this.accessToken}`,
},
});
return await res.json();
}

async put<T>(endPoint: string, body: T, querys?: QueryType) {
this.baseUrl = "/api" + endPoint;
if (querys) {
this.makeQueryString(querys);
}
const res = await fetch(querys ? this.baseUrl + this.queryString : this.baseUrl, {
method: "PUT",
body: JSON.stringify(body),
headers: {
"Content-type": "application/json",
Authorization: `Bearer ${this.accessToken}`,
},
});
return await res.json();
}

async delete(endPoint: string, querys?: QueryType) {
this.baseUrl = "/api" + endPoint;
if (querys) {
this.makeQueryString(querys);
}
const res = await fetch(querys ? this.baseUrl + this.queryString : this.baseUrl, {
method: "DELETE",
headers: {
Authorization: `Bearer ${this.accessToken}`,
},
});
return await res.json();
}
}

type GetEndPoint = "/artist/group" | `/artist/${string}` | "/group/solo" | "/reviews";
type PostEndPoint = "/event" | "/users" | "/authentication" | "/authentication/token" | "/artist" | "/group" | "/file/upload" | "/reviews";

interface QueryType {
page?: number;
size?: number;
keyword?: string;
category?: string;
}
87 changes: 82 additions & 5 deletions app/_components/bottom-sheet/StarBottomSheet.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,98 @@
import { useState } from "react";
import { PostType } from "@/(route)/(header)/post/page";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useFormContext } from "react-hook-form";
import { Api } from "@/api/api";
import { Req_Post_Type } from "@/types/reqType";
import ArtistProfile from "../artist-list/ArtistProfile";
import SearchInput from "../input/SearchInput";
import BottomSheet from "./BottomSheetMaterial";

interface Props {
closeBottomSheet: () => void;
}
const StarBottomSheet = ({ closeBottomSheet }: Props) => {
//group데이터 API 콜
const [groupId, setgroupId] = useState(""); //선택한 그룹 아이디
const [keyword, setKeyword] = useState("");
const { setValue } = useFormContext<PostType>();
const instance = new Api("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IiIsImlhdCI6MTcwNjg3Njc0NX0.J9ihWIZCBxmJGFDsT1O_Gs8XsHgdn6cczO3zGy_d2Yc");
const {
data: groupData,
isSuccess,
isLoading,
refetch: refetchGroup,
} = useQuery({
queryKey: ["group"],
queryFn: async () => {
return instance.get("/group/solo", { size: 12, page: 1 });
// return instance.post<Req_Post_Type["signup"]>("/users", {
// userName: "",
// signupMethod: "opener",
// email: "[email protected]",
// password: "asdf1234",
// myArtists: [],
// passwordCheck: "asdf1234",
// nickName: "post테스트",
// });
},
});
// const {
// data: memberData,
// isSuccess: isMemberSuccess,
// isLoading: isMemberLoading,
// refetch: refetchMember,
// } = useQuery({
// queryKey: ["member", groupId],
// queryFn: async () => {
// return api("GET", `/artist/${groupId}`);
// },
// enabled: !!groupId,
// });

console.log(keyword);
const handleGroupClick = (id: string) => {
if (!id) {
//솔로인 경우, 그냥 솔로 선택 후 바텀시트 close
return;
}
setgroupId(id);
};

const handleMemberClick = (id: string) => {};

useEffect(() => {
refetchGroup();
}, [keyword]);

// useEffect(() => {
// refetchMember();
// }, [groupId]);

console.log(groupData);

return (
<BottomSheet.Frame closeBottomSheet={closeBottomSheet}>
<div className="flex flex-col gap-20 p-20 text-16" onClick={(event) => event.stopPropagation()}>
<SearchInput setKeyword={setKeyword} />
<div>안녕 연예인 목록이야!!</div>
{/* {groupId ? (
<>
{isMemberLoading && <div>멤버 로딩중</div>}
{isMemberSuccess &&
memberData.map(({ artist_image, artist_name, artist_id }: any) => (
<ArtistProfile src={artist_image} artistName={artist_name} size={72} handleClick={() => handleMemberClick(artist_id)} />
))}
</>
) : (
<>
<SearchInput setKeyword={setKeyword} />
<div className="grid h-[360px] grid-cols-3 overflow-y-scroll">
{isLoading && <div>데이터 로딩중 ~~</div>}
{isSuccess &&
groupData.groupList.map(({ group_image, group_name, group_id }: any) => (
<ArtistProfile src={group_image} artistName={group_name} size={72} handleClick={() => handleGroupClick(group_id)} />
))}
</div>
</>
)} */}

<button className="flex h-48 items-center justify-center rounded-sm border-2 p-16">선택완료</button>
</div>
</BottomSheet.Frame>
Expand Down
73 changes: 73 additions & 0 deletions app/_types/reqType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
type Req_Post_Event = {
placeName: string;
eventType: "카페" | "팝업스토어";
groupId?: string;
artists: string[];
startDate: string;
endDate: string;
address: string;
addressDetail: string;
userId: string;
eventImages?: string[];
description?: string;
eventUrl?: string;
organizerSns?: string;
snsType?: "인스타그램" | "트위터" | "유튜브" | "기타";
tags?: string[];
isAgreed: boolean;
};

type Req_Post_Signup = {
userName?: string;
signupMethod?: string;
email: string;
password?: string;
passwordCheck?: string;
nickName?: string;
myArtists?: string[];
};

type Req_Post_Login = {
accessToken?: string;
email: string;
signinMethod: string;
password?: string;
};

type Req_Post_Token = {
accessToken: string;
refreshToken: string;
};

type Req_Post_Artist = {
artistName: string;
birthday: string;
artistImage?: string;
groups?: string[];
};

type Req_Post_Group = {
groupName: string;
debutDate: string;
groupImage?: string;
};

type Req_Post_Review = {
userId: string;
eventId: string;
isPublic?: boolean;
rating: boolean;
description: string;
reviewImages: string[];
isAgree?: boolean;
};

export type Req_Post_Type = {
event: Req_Post_Event;
signup: Req_Post_Signup;
login: Req_Post_Login;
token: Req_Post_Token;
artist: Req_Post_Artist;
group: Req_Post_Group;
review: Req_Post_Review;
};
8 changes: 8 additions & 0 deletions next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ const nextConfig = {
},
],
},
async rewrites() {
return [
{
source: "/api/:path*",
destination: `http://${process.env.NEXT_PUBLIC_BASE_URL}/:path*`,
},
];
},
};

export default nextConfig;

0 comments on commit ba6b74d

Please sign in to comment.