diff --git a/app/api/diary/route.ts b/app/api/diary/route.ts index 363f10c..9b2399d 100644 --- a/app/api/diary/route.ts +++ b/app/api/diary/route.ts @@ -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, @@ -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), { diff --git a/app/api/service/search.tsx b/app/api/service/search.tsx new file mode 100644 index 0000000..f73586d --- /dev/null +++ b/app/api/service/search.tsx @@ -0,0 +1,53 @@ +import axios from "axios"; +import { GET } from "../refresh_token/route"; + +/* + +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); + } +}; diff --git a/app/community/page.tsx b/app/community/page.tsx index c51a15f..5ee07c4 100644 --- a/app/community/page.tsx +++ b/app/community/page.tsx @@ -8,14 +8,15 @@ 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(""); // 자식에게 받을 검색어 + // 페이지 업데이트 const handleChangePage = ( event: React.ChangeEvent, value: number @@ -23,37 +24,27 @@ function CommunityPage() { setPage(value); // 페이지 변경 시 현재 페이지 상태 업데이트 }; - // [api] 모든 꿈 일기 get 요청 - const { data, error, loading } = useAxios( - "/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( - // "/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 (
@@ -62,11 +53,11 @@ function CommunityPage() {

꿈 게시글 검색

- +
- {data && data.length > 0 ? ( - data.map((d) => ( + {data?.diaries && data.diaries.length > 0 ? ( + data.diaries.map((d) => (
diff --git a/app/components/Diary/Diary.tsx b/app/components/Diary/Diary.tsx index 5e84eb4..3f576c2 100644 --- a/app/components/Diary/Diary.tsx +++ b/app/components/Diary/Diary.tsx @@ -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; @@ -18,8 +18,12 @@ export interface DiaryProps { like: number; updated_At: string; } +export interface DiaryProps { + diaries: DiaryType[]; + total: number; +} -const Diary: React.FC = ({ +const Diary = ({ id, title, isShare, @@ -27,7 +31,7 @@ const Diary: React.FC = ({ writerId, like, updated_At, -}) => { +}: DiaryType) => { return ( //writerId 넣어서 read에 보내기 diff --git a/app/components/Search/Search.tsx b/app/components/Search/Search.tsx index 9a00010..779de21 100644 --- a/app/components/Search/Search.tsx +++ b/app/components/Search/Search.tsx @@ -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(""); @@ -17,14 +22,14 @@ function CommunityPage() { const search = (event: FormEvent) => { 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 ( @@ -43,6 +48,6 @@ function CommunityPage() { ); -} +}; -export default CommunityPage; +export default Search; diff --git a/app/diary/page.tsx b/app/diary/page.tsx index 543ea01..34e968d 100644 --- a/app/diary/page.tsx +++ b/app/diary/page.tsx @@ -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, @@ -31,6 +31,7 @@ function DiaryPage() { try { const data = await getDiaryList(page, 5); setData(data); + console.log(data.diaries); } catch (error) { console.error( "다이어리 목록을 불러오는 데 실패했습니다.", @@ -40,7 +41,7 @@ function DiaryPage() { })(); }, [page]); // 페이지 번호가 변경될 때마다 리렌더링 - // console.log(data); + // console.log(data?.total); return (
@@ -62,8 +63,8 @@ function DiaryPage() {

꿈 일기 목록

- {data && data.length > 0 ? ( - data.map((d) => ( + {data.diaries && data.diaries.length > 0 ? ( + data.diaries.map((d) => ( diff --git a/app/hooks/useAxios.ts b/app/hooks/useAxios.ts index 421997d..872e71b 100644 --- a/app/hooks/useAxios.ts +++ b/app/hooks/useAxios.ts @@ -57,7 +57,6 @@ const useAxios = ( fetchData(); }, []); - return { data, loading, diff --git a/app/lib/diary.ts b/app/lib/diary.ts index dc67d6a..99cf25f 100644 --- a/app/lib/diary.ts +++ b/app/lib/diary.ts @@ -1,136 +1,138 @@ interface Comment { - content: string; - writerId: string; + content: string; + writerId: string; } -import prisma from '../../prisma/client'; -import { toKoreanTimeStamp } from '../../utils'; +import prisma from "../../prisma/client"; +import { toKoreanTimeStamp } from "../../utils"; const createNewDiary = async ({ - title, - content, - isShare, - writer, - like, + title, + content, + isShare, + writer, + like, }: { - writer: Number; - title: string; - content: string; - isShare: boolean; - like?: number; + writer: Number; + title: string; + content: string; + isShare: boolean; + like?: number; }) => { - try { - const getWriterInfo = await prisma.member.findUnique({ - where: { - id: writer + '', - }, - }); - const newDiary = await prisma.diary.create({ - data: { - writerId: writer + '', - isShare, - title: title, - contents: content, - comments: { - create: [], - }, - created_At: toKoreanTimeStamp(new Date()), - updated_At: toKoreanTimeStamp(new Date()), - like: 0, - writerName: getWriterInfo?.name, - writerPicture: getWriterInfo?.picture, - }, - }); - return newDiary; - } catch (e) { - throw e; - } + try { + const getWriterInfo = await prisma.member.findUnique({ + where: { + id: writer + "", + }, + }); + const newDiary = await prisma.diary.create({ + data: { + writerId: writer + "", + isShare, + title: title, + contents: content, + comments: { + create: [], + }, + + created_At: toKoreanTimeStamp(new Date()), + updated_At: toKoreanTimeStamp(new Date()), + like: 0, + + writerName: getWriterInfo?.name, + writerPicture: getWriterInfo?.picture, + }, + }); + return newDiary; + } catch (e) { + throw e; + } }; const getDiaryById = async (diaryId: string) => { - try { - const diary = await prisma.diary.findUnique({ - where: { - id: diaryId, - }, - include: { - comments: true, - }, - }); + try { + const diary = await prisma.diary.findUnique({ + where: { + id: diaryId, + }, + include: { + comments: true, + }, + }); - return diary; - } catch (e) { - throw new Error(JSON.stringify(e)); - } + return diary; + } catch (e) { + throw new Error(JSON.stringify(e)); + } }; const getAllDiaryByUser = async ( - userId: string, - skip?: number, - take?: number + userId: string, + skip?: number, + take?: number ) => { - try { - const allDiary = await prisma.diary.findMany({ - where: { - writerId: userId + '', - }, - skip, - take, - }); - const totalDiaries = await prisma.diary.count({ - where: { - writerId: userId, - }, - }); - console.log(allDiary, totalDiaries); + try { + const allDiary = await prisma.diary.findMany({ + where: { + writerId: userId + "", + }, + skip, + take, + }); + const totalDiaries = await prisma.diary.count({ + where: { + writerId: userId, + }, + }); + console.log(allDiary, totalDiaries); - return { - diaries: allDiary, - total: totalDiaries, - }; - } catch (e) { - throw new Error(JSON.stringify(e)); - } + return { + diaries: allDiary, + total: totalDiaries, + }; + } catch (e) { + throw new Error(JSON.stringify(e)); + } }; const deleteDiaryById = async (diaryId: string) => { - try { - await prisma.diary.delete({ - where: { - id: diaryId, - }, - }); - } catch (e) { - throw new Error(JSON.stringify(e)); - } + try { + await prisma.diary.delete({ + where: { + id: diaryId, + }, + }); + } catch (e) { + throw new Error(JSON.stringify(e)); + } }; //TODO - 댓글 업데이트 시 Diary도 업데이트하는 로직 필요. const patchDiaryById = async ( - diaryId: string, - args: Parameters + diaryId: string, + args: Parameters ) => { - const { title, content, like, isShare } = args[0]; - try { - await prisma.diary.update({ - where: { - id: diaryId, - }, - data: { - updated_At: toKoreanTimeStamp(new Date()), - like, - contents: content, - title, - isShare, - }, - }); - } catch (e) { - throw new Error(JSON.stringify(e)); - } + const { title, content, like, isShare } = args[0]; + try { + await prisma.diary.update({ + where: { + id: diaryId, + }, + data: { + updated_At: toKoreanTimeStamp(new Date()), + like, + contents: content, + title, + isShare, + }, + }); + } catch (e) { + throw new Error(JSON.stringify(e)); + } }; export { - createNewDiary, - deleteDiaryById, - patchDiaryById, - getAllDiaryByUser, - getDiaryById, + createNewDiary, + deleteDiaryById, + patchDiaryById, + getAllDiaryByUser, + getDiaryById, }; diff --git a/app/post/page.tsx b/app/post/page.tsx index ebbcac5..22a8ddd 100644 --- a/app/post/page.tsx +++ b/app/post/page.tsx @@ -36,12 +36,12 @@ function PostPage() { }; // 저장 - const handleSubmit = (event: any) => { + const handleSubmit = async (event: any) => { console.log(inputData); let boolean_share = false; if (inputData.isShare) boolean_share = true; // [api] post 요청 - postDiary(inputData.title, inputData.content, boolean_share); + await postDiary(inputData.title, inputData.content, boolean_share); // 바로 전 화면으로 이동 router.back(); }; diff --git a/app/read/[id]/page.tsx b/app/read/[id]/page.tsx index f67f754..54457dd 100644 --- a/app/read/[id]/page.tsx +++ b/app/read/[id]/page.tsx @@ -50,6 +50,8 @@ function ReadPage() { {} ); + // console.log(data); + return (
diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 8d83932..c36e0a4 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -1,72 +1,69 @@ generator client { - provider = "prisma-client-js" + provider = "prisma-client-js" previewFeatures = ["fullTextIndex"] } datasource db { provider = "mysql" url = env("DATABASE_URL") - } model Member { - //고유키 - id String @id @default(cuid()) - name String? - email String? @unique - picture String? - nickname String? - point Int @default(0) - comments Comment[] - diary Diary[] - refreshToken String? @unique + id String @id @default(cuid()) + name String? + email String? @unique + picture String? + nickname String? + point Int @default(0) + refreshToken String? @unique + comments Comment[] + diary Diary[] } model Diary { - - id String @id @default(cuid()) - title String @db.VarChar(1000) - contents String @db.VarChar(5000) - comments Comment[] - writerId String - writer Member @relation(fields: [writerId],references: [id]) - like Int @default(0) - isShare Boolean @default(true) - created_At String? - updated_At String? - writerName String? + id String @id @default(cuid()) + title String @db.VarChar(1000) + isShare Boolean @default(true) + created_At String? + updated_At String? + contents String @db.VarChar(5000) + writerId String + writerName String? writerPicture String? - - @@fulltext([title,contents]) + like Int @default(0) + comments Comment[] + writer Member @relation(fields: [writerId], references: [id]) + + @@index([writerId], map: "Diary_writerId_fkey") + @@fulltext([title, contents]) } -//댓글 모델 model Comment { - //기본키 - id String @id @default(cuid()) - comment String? - //Member의 ID를 writerID로서 참조한다.(외래 키) - writer Member @relation(fields: [writerId], references: [id]) - writerId String - //parent필드가 다른 Comment를 참조한다. (parentId가 다른 Comment의 id를 참조한다. 외래키) - parent Comment? @relation("ParentChild", fields: [parentId], references: [id], map: "CommentParent_FK") - parentId String? - //마찬가지 - children Comment[] @relation("ParentChild") - diary Diary @relation(fields: [diaryId], references: [id], map: "CommentDiary_FK" ,onDelete: Cascade) - diaryId String - created_At String? - updated_At String? - writerName String? + id String @id @default(cuid()) + writerId String + parentId String? + diaryId String + created_At String? + updated_At String? + comment String? + writerName String? writerPicture String? -} + diary Diary @relation(fields: [diaryId], references: [id], onDelete: Cascade, map: "CommentDiary_FK") + parent Comment? @relation("ParentChild", fields: [parentId], references: [id], map: "CommentParent_FK") + children Comment[] @relation("ParentChild") + writer Member @relation(fields: [writerId], references: [id]) + @@index([diaryId], map: "CommentDiary_FK") + @@index([parentId], map: "CommentParent_FK") + @@index([writerId], map: "Comment_writerId_fkey") +} model Dictionary { id String @id @default(cuid()) category String title String - contents String + contents String + @@index([category]) - @@fulltext([title,contents]) -} \ No newline at end of file + @@fulltext([title, contents]) +}