Skip to content

Commit

Permalink
Merge pull request #41 from Happy-Dreaming/feature/24
Browse files Browse the repository at this point in the history
[#24] 꿈 일기 api
  • Loading branch information
MyungJiwoo authored Apr 10, 2024
2 parents 8ba27c6 + 9d33ca5 commit 384cce9
Show file tree
Hide file tree
Showing 11 changed files with 281 additions and 226 deletions.
21 changes: 11 additions & 10 deletions app/api/diary/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@ export async function GET(req: NextRequest) {
);
}

try {
const userId = verifyToken(
cookies().get('dreaming_accessToken')?.value ?? ''
).userId;
const getAllPosts = await getAllDiaryByUser(
userId + '',
parseInt(skip + ''),
parseInt(pageSize as string)
);
console.log(getAllPosts);
try {
const userId = verifyToken(
cookies().get("dreaming_accessToken")?.value ?? ""
).userId;
const getAllPosts = await getAllDiaryByUser(
userId + "",
parseInt(skip + ""),
parseInt(pageSize as string)
);
console.log(getAllPosts);
if (userId && getAllPosts) {
return new Response(JSON.stringify(getAllPosts), {
status: 200,
Expand Down Expand Up @@ -110,6 +110,7 @@ export async function POST(req: NextRequest) {
isShare,
writer: Number(decodedToken?.userId),
});
console.log(newPost);

await addUserPoints(userId + "");
return new Response(JSON.stringify(newPost), {
Expand Down
53 changes: 53 additions & 0 deletions app/api/service/search.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import axios from "axios";
import { GET } from "../refresh_token/route";

/*
<search 관련 api>
1. 꿈 일기 검색
2. 꿈 해몽 검색
*/

// [get] 꿈 일기 검색
export const getSearchDiary = async (search: string, page: number) => {
try {
const response = await axios({
method: "GET",
url: "/api/diaries",
params: {
search: search,
page: page,
},
});
// 응답 결과 : 다이어리[]
console.log(response.data);

return response.data;
} catch (error) {
console.log(error);
}
};

// [get] 꿈 해몽 검색
export const getSearchDictionary = async (
keyword: string,
page: number,
pageSize: number
) => {
try {
const response = await axios({
method: "GET",
url: `/api/dictionary/search`,
params: {
keyword: keyword,
page: page,
pageSize: pageSize,
},
});
// 응답 결과 : 꿈 해몽[]
console.log(response.data);

return response.data;
} catch (error) {
console.log(error);
}
};
65 changes: 28 additions & 37 deletions app/community/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,52 +8,43 @@ import Diary, { DiaryProps } from "../components/Diary/Diary";
import Search from "../components/Search/Search";
import { useAxios } from "../hooks/useAxios";
import { useRouter } from "next/router";
import { getSearchDiary } from "../api/service/search";

function CommunityPage() {
const [page, setPage] = useState(1); // 현재 페이지
const [totalPages, setTotalPages] = useState(0); // 총 데이터 수
// const [results, setResults] = useState([]); // 검색
// const router = useRouter(); // 검색
// const { keyword } = router.query; // 검색
const [data, setData] = useState([]);
const [searchKeyword, setSearchKeyword] = useState<string>(""); // 자식에게 받을 검색어

// 페이지 업데이트
const handleChangePage = (
event: React.ChangeEvent<unknown>,
value: number
) => {
setPage(value); // 페이지 변경 시 현재 페이지 상태 업데이트
};

// [api] 모든 꿈 일기 get 요청
const { data, error, loading } = useAxios<DiaryProps[]>(
"/api/diaries",
"get",
{},
{
params: {
keyword: "",
page: 1,
},
}
);

console.log(data);
// 검색바 -> 검색어 업데이트
const handleSearchKeyword = (result: string) => {
setSearchKeyword(result);
console.log(result);
};

// [api] 검색
// useEffect(() => {
// if (keyword) {
// const { data, error, loading } = useAxios<DiaryProps[]>(
// "/api/diaries",
// "get",
// {},
// {
// params: {
// keyword: "",
// page: 1,
// },
// }
// );
// }
// }, [keyword]);
// [api] 꿈 일기 목록 get 요청
useEffect(() => {
(async () => {
try {
const data = await getSearchDiary(searchKeyword, page);
setData(data);
console.log(data.diaries);
} catch (error) {
console.error(
"다이어리 목록을 불러오는 데 실패했습니다.",
error
);
}
})();
}, [page, searchKeyword]); // 페이지 번호가 변경될 때마다 리렌더링

return (
<div className={styles.container}>
Expand All @@ -62,11 +53,11 @@ function CommunityPage() {
</div>
<div className={styles.searchBox}>
<p className={styles.searchTitle}>꿈 게시글 검색</p>
<Search />
<Search onSearchKeyword={handleSearchKeyword} />
</div>
<div className={styles.posts}>
{data && data.length > 0 ? (
data.map((d) => (
{data?.diaries && data.diaries.length > 0 ? (
data.diaries.map((d) => (
<Diary
key={d.id}
id={d.id}
Expand All @@ -84,7 +75,7 @@ function CommunityPage() {
</div>
<div className={styles.pagination}>
<BasicPagination
count={Math.round(page / 2)}
count={Math.ceil(data?.total / 15)}
page={page}
onChange={handleChangePage}
/>
Expand Down
10 changes: 7 additions & 3 deletions app/components/Diary/Diary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { BsFillPersonFill } from "react-icons/bs";
import { BsHeartFill } from "react-icons/bs";
import { BsChatDotsFill } from "react-icons/bs";

export interface DiaryProps {
export interface DiaryType {
id: string;
title: string;
isShare: boolean;
Expand All @@ -18,16 +18,20 @@ export interface DiaryProps {
like: number;
updated_At: string;
}
export interface DiaryProps {
diaries: DiaryType[];
total: number;
}

const Diary: React.FC<DiaryProps> = ({
const Diary = ({
id,
title,
isShare,
contents,
writerId,
like,
updated_At,
}) => {
}: DiaryType) => {
return (
//writerId 넣어서 read에 보내기
<Link href={`/read/${id}`}>
Expand Down
27 changes: 16 additions & 11 deletions app/components/Search/Search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@
import React, { ChangeEvent, FormEvent, useState } from "react";
import styles from "./Search.module.css";
import { useRouter } from "next/router";
import { getSearchDiary, getSearchDictionary } from "../../api/service/search";

function CommunityPage() {
interface SearchProps {
onSearchKeyword: (keyword: string) => void;
}

const Search = ({ onSearchKeyword }: SearchProps) => {
// 검색
const [inputKeyword, setInputKeyword] = useState("");
const [searchKeyword, setSearchKeyword] = useState("");
Expand All @@ -17,14 +22,14 @@ function CommunityPage() {
const search = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setSearchKeyword(inputKeyword);
console.log(inputKeyword);

// if (inputKeyword.trim()) {
// router.push({
// pathname: "/community",
// query: { keyword: inputKeyword },
// });
// }
// console.log(inputKeyword);

// 꿈 일기 검색
// getSearchDiary(inputKeyword, 1);

// 꿈 사전 검색
// getSearchDictionary(inputKeyword, 1, 5);
onSearchKeyword(inputKeyword);
};

return (
Expand All @@ -43,6 +48,6 @@ function CommunityPage() {
</form>
</>
);
}
};

export default CommunityPage;
export default Search;
11 changes: 6 additions & 5 deletions app/diary/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function DiaryPage() {
const [page, setPage] = useState(1); // 현재 페이지
// cosnt [pagesize, setPagezize]
const [totalPages, setTotalPages] = useState(0); // 총 데이터 수
const [data, setData] = useState();
const [data, setData] = useState([]);

const handleChangePage = (
event: React.ChangeEvent<unknown>,
Expand All @@ -31,6 +31,7 @@ function DiaryPage() {
try {
const data = await getDiaryList(page, 5);
setData(data);
console.log(data.diaries);
} catch (error) {
console.error(
"다이어리 목록을 불러오는 데 실패했습니다.",
Expand All @@ -40,7 +41,7 @@ function DiaryPage() {
})();
}, [page]); // 페이지 번호가 변경될 때마다 리렌더링

// console.log(data);
// console.log(data?.total);

return (
<div className={styles.container}>
Expand All @@ -62,8 +63,8 @@ function DiaryPage() {

<div className={styles.postBox}>
<p className={styles.postsTitle}>꿈 일기 목록</p>
{data && data.length > 0 ? (
data.map((d) => (
{data.diaries && data.diaries.length > 0 ? (
data.diaries.map((d) => (
<Diary
key={d.id}
id={d.id}
Expand All @@ -82,7 +83,7 @@ function DiaryPage() {
{/* 페이지네이션 */}
<div className={styles.pagination}>
<BasicPagination
count={5}
count={Math.ceil(data.total / 5)}
page={page}
onChange={handleChangePage}
/>
Expand Down
1 change: 0 additions & 1 deletion app/hooks/useAxios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ const useAxios = <T>(
fetchData();
}, []);


return {
data,
loading,
Expand Down
Loading

0 comments on commit 384cce9

Please sign in to comment.