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

[정진호] week19 #552

Merged
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
20 changes: 20 additions & 0 deletions apis/instance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";

const instance = axios.create({
baseURL: "https://bootcamp-api.codeit.kr/api/linkbrary/v1",
timeout: 10000,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ㅗㅜㅑ 타임아웃까지 설정하시는 디테일 ~ 좋습니다 👍

});

export const request = (config: AxiosRequestConfig) => {
const client = instance;
return client(config);
};
Comment on lines +8 to +11
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

현재 코드에서 client를 선언하는 것은 의미가 없어보입니다 !

Suggested change
export const request = (config: AxiosRequestConfig) => {
const client = instance;
return client(config);
};
export const request = (config: AxiosRequestConfig) => {
return instance(config);
};


const fetcher = async <T>(config: AxiosRequestConfig) => {
const response = await request({ ...config });
const { data, status }: { data: T; status: number } = response;

return { data, status };
};

export default fetcher;
71 changes: 71 additions & 0 deletions apis/queryClientProvider.ts
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

복붙의 향기가 느껴진다.. 여기 taskify인가요?

Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { getAccessToken } from "@/business/getAccessToken";
import { QueryClient } from "@tanstack/react-query";
import { GetServerSidePropsContext } from "next";
import { FolderById, Folders, Link, User, UserById } from "@/types/server.type";
import fetcher from "./instance";

export const queryClientProvider = async (context: GetServerSidePropsContext) => {
const queryClient = new QueryClient();

const accessToken = getAccessToken(context) as string;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

타입 어설션을 사용하지 않고 반환 타입을 명시하는게 어떨까요?

Suggested change
const accessToken = getAccessToken(context) as string;
const accessToken = getAccessToken(context);
// getAccessToken.ts
import { GetServerSidePropsContext } from "next";

export const getAccessToken = (context: GetServerSidePropsContext): string => {
  const accessToken = context.req.cookies["accessToken"];

  return accessToken ?? "";
};

진호님이라면 아실 수 있지만 타입스크립트에서는 흔히 도는 말이 있습니다!

  1. any 타입을 사용하지 말 것.
  2. 타입 어설션을 사용하지 말 것.

물론 생산성을 위해서 사용될 수도 있지만 사용 안하는걸 인지하고 있는 것도 좋을 것 같아서 제안드립니다 =)
만약 앞으로 타입 어설션을 사용하지 않으려 할 때 문제가 생긴다면 타입 가드가 유용한 대체가 될 수 있습니다.

참고 자료


const url = context.req.url as string;

await queryClient.prefetchQuery({
queryKey: ["currentUser"],
queryFn: () => fetcher<User[]>({ method: "get", url: "/users", headers: { Authorization: accessToken } }),
});

const folder_ID = context.query["id"];

if (folder_ID) {
const folderData = await queryClient.fetchQuery({
queryKey: ["FolderById", folder_ID],
queryFn: () => fetcher<FolderById[]>({ method: "get", url: `/folders/${folder_ID}` }),
});

const [{ user_id: user_ID }] = folderData?.data ?? [];

if (user_ID) {
await queryClient.prefetchQuery({
queryKey: ["userById", user_ID],
queryFn: () => fetcher<UserById[]>({ method: "get", url: `/users/${user_ID}` }),
});

await queryClient.prefetchQuery({
queryKey: ["LinkById", folder_ID],
queryFn: () => fetcher<Link[]>({ method: "get", url: `/folders/${folder_ID}/links` }),
});
}
}

if (url === "/folder") {
const folderData = await queryClient.fetchQuery({
queryKey: ["Folders"],
queryFn: () => fetcher<Folders[]>({ method: "get", url: "/folders", headers: { Authorization: accessToken } }),
});

if (folderData?.data) {
await queryClient.prefetchQuery({
queryKey: ["Links", 0],
queryFn: () => fetcher<Link[]>({ method: "get", url: `/links`, headers: { Authorization: accessToken } }),
});

folderData.data.forEach(async (data) => {
const folder_Id = data.id;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

일관된 코드 컨벤션을 사용하시는게 좋을 것 같아요 !

Suggested change
const folder_Id = data.id;
const folderId = data.id;


await queryClient.prefetchQuery({
queryKey: ["Links", folder_Id],
queryFn: () =>
fetcher<Link[]>({
method: "get",
url: `/folders/${folder_Id}/links`,
headers: { Authorization: accessToken },
}),
});
});
}
Comment on lines +54 to +67
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ㅋㅋㅋㅋ SSR을 국물 한 모금도 안 남기고 사용하려는 거 같아서 웃겨요
forEach로 폴더별 링크까지 싸그리싹싹 가져온다..

}

return { queryClient, accessToken };
};
7 changes: 7 additions & 0 deletions business/getAccessToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { GetServerSidePropsContext } from "next";

export const getAccessToken = (context: GetServerSidePropsContext) => {
const accessToken = context.req.cookies["accessToken"];

return accessToken ?? "";
};
74 changes: 74 additions & 0 deletions business/sign/signError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { handleInputErrorFunc } from "@/types/client.type";
import { isEmail, isPassword } from "./validation";
import instance from "@/apis/instance";

const errorText = {
email: {
null: "이메일을 입력해주세요",
wrong: "올바른 이메일 주소가 아닙니다",
dup: "이미 사용 중인 이메일입니다",
},
password: {
null: "비밀번호를 입력해주세요",
wrong: "비밀번호는 영문, 숫자 조합 8자 이상 입력해 주세요",
},
passwordCheck: {
wrong: "비밀번호가 일치하지 않아요",
},
};
Comment on lines +5 to +18
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

밸리데이션 문구를 따로 빼놓으셨군요 👍 가독성 측면에서 매우 좋습니다.

다음에는 유효성 검사 툴인 joi를 사용해보는 것도 추천드려요 !


const checkEmail = async (value: string) => {
const response = await instance.post("/users/check-email", { data: { email: value } });

return response.status === 409;
};

const signinEmail = ({ value, setErrorText }: handleInputErrorFunc) => {
if (value === "") {
setErrorText(errorText["email"]["null"]);
} else if (!isEmail(value)) {
setErrorText(errorText["email"]["wrong"]);
} else {
setErrorText("");
}
};

const signinPassword = ({ value, setErrorText }: handleInputErrorFunc) => {
if (value === "") {
setErrorText(errorText["password"]["null"]);
} else {
setErrorText("");
}
};

const signupEmail = async ({ value, setErrorText }: handleInputErrorFunc) => {
if (value === "") {
setErrorText(errorText["email"]["null"]);
} else if (!isEmail(value)) {
setErrorText(errorText["email"]["wrong"]);
} else if (await checkEmail(value)) {
setErrorText(errorText["email"]["dup"]);
} else {
setErrorText("");
}
};

const signupPassword = ({ value, setErrorText }: handleInputErrorFunc) => {
if (value === "") {
setErrorText(errorText["password"]["null"]);
} else if (!isPassword(value)) {
setErrorText(errorText["password"]["wrong"]);
} else {
setErrorText("");
}
};

const signupPasswordCheck = ({ value, setErrorText, valueToCompare }: handleInputErrorFunc) => {
if (value !== valueToCompare) {
setErrorText(errorText["passwordCheck"]["wrong"]);
} else {
setErrorText("");
}
};

export { signinEmail, signinPassword, signupEmail, signupPassword, signupPasswordCheck };
11 changes: 11 additions & 0 deletions business/sign/validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const isEmail = (input: string) => {
const emailRegex = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;
return emailRegex.test(input);
};

const isPassword = (input: string) => {
const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d).{8,}$/;
return passwordRegex.test(input);
};

export { isEmail, isPassword };
57 changes: 21 additions & 36 deletions components/Binder/Binder.tsx
Original file line number Diff line number Diff line change
@@ -1,56 +1,41 @@
import styles from "./Binder.module.css";
import Card from "../Card/Card";
import { Dispatch, FormEvent, MouseEvent, SetStateAction, useCallback, useEffect, useState } from "react";
import { Linkinfo } from "@/API/getLinksByFolderID";
import { Link } from "@/types/server.type";
import { Dispatch, FormEvent, MouseEvent, SetStateAction, useEffect, useState } from "react";
import Card from "./Card/Card";
import EmptyNoti from "./EmptyNoti/EmptyNoti";

interface Props {
cards: Linkinfo[];
cards: Link[];
shared?: Boolean;
handleClick?: (e: MouseEvent | FormEvent) => void;
setTarget?: Dispatch<SetStateAction<string | null | undefined>>;
setTargetURL?: React.Dispatch<React.SetStateAction<string>>;
value: string;
}

function Binder({ cards, shared = false, value: searchValue, handleClick, setTarget, setTargetURL }: Props) {
const [links, setLinks] = useState(cards);

const handleButtonClick = (e: MouseEvent | FormEvent, targetName: string) => {
if (handleClick && setTarget) {
handleClick(e);
setTarget(targetName);
}
};

const filterLinks = useCallback(
(searchValue: string) => {
const filteredLinks = cards.filter(
(link) =>
link.url?.toLowerCase().includes(searchValue.toLowerCase()) ||
link.title?.toLowerCase().includes(searchValue.toLowerCase()) ||
link.description?.toLowerCase().includes(searchValue.toLowerCase())
);
setLinks(filteredLinks);
},
[cards]
const filterLinks = (searchValue: string, setLinks: Dispatch<SetStateAction<Link[]>>, cards: Link[]) => {
const filteredLinks = cards.filter(
(link) =>
link.url?.toLowerCase().includes(searchValue.toLowerCase()) ||
link.title?.toLowerCase().includes(searchValue.toLowerCase()) ||
link.description?.toLowerCase().includes(searchValue.toLowerCase())
Comment on lines +17 to +19
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이거 배열로 처리하면 코드 중복 줄어요~

[link.url, link.title, link,description]
.map(value => value.toLowerCase())
.some(value => value.includes(searchValue.toLowerCase()))

참고로 배열 메서드도 Promise .then 체이닝처럼 엔터키 치고 줄마다 메서드 써도 됩니당

);
setLinks(filteredLinks);
};

function Binder({ cards, shared = false, value: searchValue }: Props) {
const [links, setLinks] = useState(cards);

useEffect(() => {
filterLinks(searchValue);
}, [searchValue, filterLinks]);
filterLinks(searchValue, setLinks, cards);
}, [searchValue, cards]);

if (cards.length === 0) return <EmptyNoti />;

return (
<article className={styles.root}>
{links.map((card) => {
return (
<li className={styles.cardContainer} key={card.id}>
<Card
card={card}
setTargetURL={setTargetURL}
shared={shared}
deleteLink={(e) => handleButtonClick(e, "deleteLink")}
addLinkToFolder={(e) => handleButtonClick(e, "AddLinkToFolderFromCard")}
/>
<Card card={card} shared={shared} />
</li>
);
})}
Expand Down
106 changes: 106 additions & 0 deletions components/Binder/Card/Card.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
.root {
width: 34rem;
height: 33.4rem;
border-radius: 1.5rem;
box-shadow: 0px 5px 25px 0px rgba(0, 0, 0, 0.08);
}

.image {
width: 100%;
height: 20rem;
border-top-right-radius: 1.5rem;
border-top-left-radius: 1.5rem;
background-position: center;
background-size: 112%;
display: flex;
flex-direction: row-reverse;
align-items: flex-start;
}

.star {
width: 3.4rem;
height: 3.4rem;
margin: 1.5rem;
}

.deleteButton {
font-size: 1.6rem;
width: 100%;
padding: 1.6rem 2rem;
background: var(--error);
}

.addButton {
font-size: 1.6rem;
width: 100%;
padding: 1.6rem 2rem;
}

@keyframes hoverImageSizeChanger {
from {
background-size: 112%;
}

to {
background-size: 125%;
}
}

.hoverImage {
animation: hoverImageSizeChanger 0.25s ease-in-out forwards;
}

.hoverBgColor {
background-color: #f0f6ff;
}

.explanation {
display: flex;
flex-direction: column;
padding: 1.5rem 2rem;
gap: 1rem;
}

.header {
display: flex;
font-size: 1.3rem;
color: #666;
justify-content: space-between;
}

.text {
font-size: 1.6rem;
width: 30rem;
line-height: 24px;
height: 4.9rem;
}

.text div {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 1.6rem;
}

.footer {
height: 1.9rem;
font-size: 1.4rem;
}

@media (max-width: 1191px) {
.text {
width: 100%;
max-width: 35vw;
}

.root {
width: 100%;
}
}

@media (max-width: 767px) {
.text {
width: 100%;
max-width: 55vw;
}
}
Loading