Commit 8b8c6f9c authored by Yoon, Daeki's avatar Yoon, Daeki 😅
Browse files

Merge branch 'jiwon0715' into main-jiwon

parents 6b56633c a4cbdf12
...@@ -21,7 +21,9 @@ export const updateQuestion = async (question: BasicQuestionType) => { ...@@ -21,7 +21,9 @@ export const updateQuestion = async (question: BasicQuestionType) => {
return data; return data;
}; };
export const deleteQuestion = async (id: string) => { export const deleteQuestion = async (questionId: string) => {
const { data } = await axios.delete(`${baseUrl}/questions/delete/${id}`); const { data } = await axios.delete(
`${baseUrl}/questions/delete/${questionId}`
);
return data; return data;
}; };
...@@ -11,6 +11,11 @@ export const getSurvey = async (surveyId: string) => { ...@@ -11,6 +11,11 @@ export const getSurvey = async (surveyId: string) => {
const { data } = await axios.get(`${baseUrl}/surveys/edit/${surveyId}`); const { data } = await axios.get(`${baseUrl}/surveys/edit/${surveyId}`);
return data; return data;
}; };
//동혁
export const getSurveys = async () => {
const { data } = await axios.get(`${baseUrl}/surveys/`);
return data;
};
export const editSurvey = async (survey: SurveyType) => { export const editSurvey = async (survey: SurveyType) => {
const { data } = await axios.put( const { data } = await axios.put(
...@@ -19,3 +24,8 @@ export const editSurvey = async (survey: SurveyType) => { ...@@ -19,3 +24,8 @@ export const editSurvey = async (survey: SurveyType) => {
); );
return data; return data;
}; };
export const deleteSurvey = async (surveyId: string) => {
const { data } = await axios.delete(`${baseUrl}/surveys/delete/${surveyId}`);
return data;
};
...@@ -14,37 +14,30 @@ export const Header = () => { ...@@ -14,37 +14,30 @@ export const Header = () => {
</Link> </Link>
<div className="md:flex items-center justify-end md:flex-1 lg:w-0"> <div className="md:flex items-center justify-end md:flex-1 lg:w-0">
{user.isLoggedIn ? ( {user.isLoggedIn ? (
<div className=""> <div>
<button <button
onClick={() => logout()} onClick={() => logout()}
className="whitespace-nowrap font-bold text-gray-600 hover:text-themeColor mx-1 py-2 px-3 rounded-md" className="font-bold text-gray-600 hover:text-themeColor mx-1 py-2 px-3 rounded-md"
> >
로그아웃 로그아웃
</button> </button>
{location.pathname === "/profile" ? ( <Link to="/profile">
"" <button className="font-bold text-gray-600 hover:text-themeColor mx-1 py-2 px-3 rounded-md">
) : (
<Link
to="/profile"
className="whitespace-nowrap font-bold text-gray-600 hover:text-themeColor mx-1 py-2 px-3 rounded-md"
>
프로필 프로필
</Link> </button>
)} </Link>
</div> </div>
) : ( ) : (
<div> <div>
<Link <Link to="/login">
to="/login" <button className="font-bold text-gray-600 hover:text-themeColor mx-1 py-2 px-3 rounded-md">
className="whitespace-nowrap font-bold text-gray-600 hover:text-themeColor mx-1 py-2 px-3 rounded-md" 로그인
> </button>
로그인
</Link> </Link>
<Link <Link to="/signup">
to="/signup" <button className="font-bold text-white hover:bg-blue-500 mx-1 py-2 px-3 bg-themeColor rounded-md ">
className="whitespace-nowrap font-bold text-white hover:bg-blue-500 mx-1 py-2 px-3 bg-themeColor rounded-md " 회원가입
> </button>
회원가입
</Link> </Link>
</div> </div>
)} )}
......
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { surveyApi } from "../apis";
import { SurveyType } from "../types";
import { catchErrors } from "../helpers";
type Props = {
data: SurveyType;
};
export const MySurveyCard = ({ data }: Props) => {
const navigate = useNavigate();
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false);
const editSurvey = () => {
navigate(`/surveys/edit/${data._id}`, {
replace: true,
});
};
async function deleteSurvey() {
try {
if (data._id) {
const survey = await surveyApi.deleteSurvey(data._id);
setSuccess(true);
setError("");
location.reload();
} else {
setLoading(true);
}
} catch (error) {
console.log("에러발생");
catchErrors(error, setError);
} finally {
setLoading(false);
}
}
return (
<div className="w-52 h-60 rounded border-2">
<div className="h-32 p-5">
<p className="text-gray-700">
{data.comment ? data.comment : "설명없는 설문조사"}
</p>
</div>
<div className="flex flex-col px-5 py-3">
<div className="h-12">
<p className="font-bold">
{data.title ? data.title : "제목없는 설문조사"}
</p>
<p className="text-gray-500 text-sm">
{data.updatedAt?.substring(0, 10)}
</p>
</div>
<div className="flex justify-end pt-1">
<button
type="button"
className="bg-themeColor rounded text-white py-1 px-1.5 mr-1"
onClick={editSurvey}
>
수정
</button>
<button
type="button"
className="bg-themeColor rounded text-white py-1 px-1.5 ml-1"
onClick={deleteSurvey}
>
삭제
</button>
</div>
</div>
</div>
);
};
import React, { useState } from "react"; import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { baseImageUrl, surveyApi } from "../apis"; import { baseImageUrl, surveyApi } from "../apis";
import { SurveyType } from "../types"; import { SurveyType } from "../types";
import { MySurveyCard } from "./MySurveyCard";
export const Profile = () => { export const Profile = () => {
const navigate = useNavigate(); const navigate = useNavigate();
...@@ -11,6 +12,12 @@ export const Profile = () => { ...@@ -11,6 +12,12 @@ export const Profile = () => {
comment: "", comment: "",
questions: [], questions: [],
}); });
const [cardDatas, setCardDatas] = useState<SurveyType[]>([]);
useEffect(() => {
getSurveys();
}, []);
async function createSurvey() { async function createSurvey() {
const newSurvey: SurveyType = await surveyApi.createSurvey(survey); const newSurvey: SurveyType = await surveyApi.createSurvey(survey);
navigate(`/surveys/edit/${newSurvey._id}`, { navigate(`/surveys/edit/${newSurvey._id}`, {
...@@ -18,95 +25,29 @@ export const Profile = () => { ...@@ -18,95 +25,29 @@ export const Profile = () => {
}); });
} }
async function getSurveys() {
const surveys: SurveyType[] = await surveyApi.getSurveys();
console.log(surveys);
setCardDatas(surveys);
}
// let surveys = getSurvey(_id);
return ( return (
<div className="flex flex-col items-center"> <div className="flex flex-col items-center">
<div className="m-5">나의 설문조사</div> <div className="mt-10 text-xl font-bold">나의 설문조사</div>
<img src={`${baseImageUrl}/9e24ad36a2947b08c89913b01`} /> <img src={`${baseImageUrl}/9e24ad36a2947b08c89913b01`} />
<div className="flex space-x-4 mt-5"> <div className="flex space-x-4 mt-6">
<button <button
onClick={createSurvey} onClick={createSurvey}
className="flex h-60 w-48 items-center border-2 border-themeColor font-bold bg-gray-200 hover:bg-themeColor rounded-lg " className="flex h-60 w-52 items-center border-2 border-themeColor font-bold bg-gray-200 hover:bg-themeColor rounded-lg "
> >
<div className="text-center px-6 py-6 font-bold text-gray-500 place-items-center hover:text-white"> <div className="text-center px-6 py-6 font-bold text-gray-500 place-items-center hover:text-white">
CREATE NEW SURVEY! CREATE NEW SURVEY!
</div> </div>
</button> </button>
<div className="w-48 h-60 rounded overflow-hidden border-2"> {cardDatas.map((data, index) => {
<div className="px-6 py-4"> return <MySurveyCard data={data} key={index} />;
<p className="text-gray-700 text-base"> })}
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
</p>
</div>
<div className="flex flex-col py-6">
<div className="px-2 py-2">
<label>설문조사 이름</label>
</div>
<div className="flex justify-end">
<select className="py-2 w-14 bg-themeColor rounded text-white">
<option selected>옵션</option>
<option>삭제</option>
<option>이름 바꾸기</option>
</select>
</div>
</div>
</div>
<div className="w-48 h-60 rounded overflow-hidden border-2">
<div className="px-6 py-4">
<p className="text-gray-700 text-base">
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
</p>
</div>
<div className="flex flex-col py-6">
<div className="px-2 py-2">
<label>설문조사이름</label>
</div>
<div className="flex justify-end">
<select className="py-2 w-14 bg-themeColor rounded text-white">
<option selected>옵션</option>
<option>삭제</option>
<option>이름 바꾸기</option>
</select>
</div>
</div>
</div>
<div className="w-48 h-60 rounded overflow-hidden border-2">
<div className="px-6 py-4">
<p className="text-gray-700 text-base">
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
</p>
</div>
<div className="flex flex-col py-6">
<div className="px-2 py-2">
<label>설문조사 이름</label>
</div>
<div className="flex justify-end">
<select className="py-2 w-14 bg-themeColor rounded text-white">
<option selected>옵션</option>
<option>삭제</option>
<option>이름 바꾸기</option>
</select>
</div>
</div>
</div>
<div className="w-48 h-60 rounded overflow-hidden border-2">
<div className="px-6 py-4">
<p className="text-gray-700 text-base">
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
</p>
</div>
<div className="flex flex-col py-6">
<div className="px-2 py-2">
<label>설문조사 이름</label>
</div>
<div className="flex justify-end">
<select className="py-2 w-14 bg-themeColor rounded text-white">
<option selected>옵션</option>
<option>삭제</option>
<option>이름 바꾸기</option>
</select>
</div>
</div>
</div>
</div> </div>
</div> </div>
); );
......
...@@ -34,9 +34,6 @@ export const Question = ({ ...@@ -34,9 +34,6 @@ export const Question = ({
changeCurrentId, changeCurrentId,
currentId, currentId,
}: Props) => { }: Props) => {
const handleEditClick = () => {
changeCurrentId(element._id);
};
async function handleEditComplete() { async function handleEditComplete() {
try { try {
const newQuestion: BasicQuestionType = await questionApi.updateQuestion( const newQuestion: BasicQuestionType = await questionApi.updateQuestion(
...@@ -92,10 +89,6 @@ export const Question = ({ ...@@ -92,10 +89,6 @@ export const Question = ({
handleQuestion(element._id); handleQuestion(element._id);
} }
function handleDelete() {
deleteQuestion(element._id);
}
function getContent(element: BasicQuestionType) { function getContent(element: BasicQuestionType) {
switch (element.type) { switch (element.type) {
case "essay": case "essay":
...@@ -138,9 +131,22 @@ export const Question = ({ ...@@ -138,9 +131,22 @@ export const Question = ({
return <></>; return <></>;
} }
} }
const handleRequired = (event: React.ChangeEvent<HTMLInputElement>) => {
const { checked, value } = event.currentTarget;
element[value] = checked;
handleQuestion(element._id);
};
const handleDelete = () => {
deleteQuestion(element._id);
};
const handleEditClick = () => {
changeCurrentId(element._id);
};
return ( return (
<div className="flex flex-col container w-4/5 h-auto border-2 border-themeColor items-center m-3 py-2"> <div
style={{ borderColor: currentId === element._id ? "red" : "#58ACFA" }}
className="flex flex-col container w-4/5 h-auto border-2 items-center m-3 py-2"
>
<div className="flex h-16 w-full place-content-between items-center"> <div className="flex h-16 w-full place-content-between items-center">
<input <input
type="text" type="text"
...@@ -184,12 +190,17 @@ export const Question = ({ ...@@ -184,12 +190,17 @@ export const Question = ({
{getContent(element)} {getContent(element)}
<div className="place-self-end py-2"> <div className="place-self-end py-2">
<button type="button" className="px-1"> <input
type="checkbox"
id="isRequired"
value="isRequired"
onChange={handleRequired}
disabled={currentId !== element._id}
checked={element.isRequired}
/>
<label htmlFor="isRequired" className="px-1">
필수 필수
</button> </label>
<button type="button" className="px-1">
옵션
</button>
<button type="button" className="px-1" onClick={handleDelete}> <button type="button" className="px-1" onClick={handleDelete}>
삭제 삭제
</button> </button>
......
...@@ -31,7 +31,7 @@ export const RatingForm = ({ element, handleQuestion, currentId }: Props) => { ...@@ -31,7 +31,7 @@ export const RatingForm = ({ element, handleQuestion, currentId }: Props) => {
handleQuestion(element._id); handleQuestion(element._id);
} }
function addValue() { function addValue() {
choices.push({ text: "0", value: choices.length }); choices.push({ text: "", value: choices.length });
element.content.choices = choices; element.content.choices = choices;
handleQuestion(element._id); handleQuestion(element._id);
} }
......
import React, { FormEvent, useEffect, useState } from "react"; import React, { FormEvent, useEffect, useState } from "react";
import { useParams } from "react-router-dom"; import { useParams, useNavigate } from "react-router-dom";
import { questionApi, surveyApi } from "../apis"; import { questionApi, surveyApi } from "../apis";
import { SpinnerIcon } from "../icons"; import { SpinnerIcon } from "../icons";
import { Question } from "../questions"; import { Question } from "../questions";
import { BasicQuestionType, SurveyType } from "../types"; import { BasicQuestionType, SurveyType } from "../types";
import { catchErrors } from "../helpers";
export const EditSurvey = () => { export const EditSurvey = () => {
let { surveyId } = useParams<{ surveyId: string }>(); let { surveyId } = useParams<{ surveyId: string }>();
const navigate = useNavigate();
useEffect(() => { useEffect(() => {
getSurvey(); getSurvey();
}, [surveyId]); }, [surveyId]);
...@@ -35,8 +37,10 @@ export const EditSurvey = () => { ...@@ -35,8 +37,10 @@ export const EditSurvey = () => {
setLoading(true); setLoading(true);
} }
} catch (error) { } catch (error) {
console.log("에러발생"); catchErrors(error, setError);
// catchErrors(error, setError) // navigate(`/`, {
// replace: false,
// });
} finally { } finally {
setLoading(false); setLoading(false);
} }
...@@ -57,13 +61,12 @@ export const EditSurvey = () => { ...@@ -57,13 +61,12 @@ export const EditSurvey = () => {
try { try {
const newSurvey: SurveyType = await surveyApi.editSurvey(survey); const newSurvey: SurveyType = await surveyApi.editSurvey(survey);
console.log(newSurvey); console.log(newSurvey);
// setSuccess(true); setSuccess(true);
// setError(""); setError("");
} catch (error) { } catch (error) {
console.log("에러발생"); catchErrors(error, setError);
// catchErrors(error, setError)
} finally { } finally {
// setLoading(false); setLoading(false);
} }
} }
...@@ -71,13 +74,12 @@ export const EditSurvey = () => { ...@@ -71,13 +74,12 @@ export const EditSurvey = () => {
try { try {
const newQuestion: BasicQuestionType = await questionApi.createQuestion(); const newQuestion: BasicQuestionType = await questionApi.createQuestion();
setSurvey({ ...survey, questions: [...survey.questions, newQuestion] }); setSurvey({ ...survey, questions: [...survey.questions, newQuestion] });
// setSuccess(true); setSuccess(true);
// setError(""); setError("");
} catch (error) { } catch (error) {
console.log("에러발생"); catchErrors(error, setError);
// catchErrors(error, setError)
} finally { } finally {
// setLoading(false); setLoading(false);
} }
} }
...@@ -88,13 +90,12 @@ export const EditSurvey = () => { ...@@ -88,13 +90,12 @@ export const EditSurvey = () => {
id id
); );
setSurvey({ ...survey, questions: newList.filter((a) => a._id !== id) }); setSurvey({ ...survey, questions: newList.filter((a) => a._id !== id) });
// setSuccess(true); setSuccess(true);
// setError(""); setError("");
} catch (error) { } catch (error) {
console.log("에러발생"); catchErrors(error, setError);
// catchErrors(error, setError)
} finally { } finally {
// setLoading(false); setLoading(false);
} }
} }
...@@ -102,6 +103,7 @@ export const EditSurvey = () => { ...@@ -102,6 +103,7 @@ export const EditSurvey = () => {
console.log(questions); console.log(questions);
return ( return (
<> <>
{error ? alert(error) : <></>}
{loading && ( {loading && (
<SpinnerIcon className="animate-spin h-5 w-5 mr-1 text-slate" /> <SpinnerIcon className="animate-spin h-5 w-5 mr-1 text-slate" />
)} )}
...@@ -113,6 +115,7 @@ export const EditSurvey = () => { ...@@ -113,6 +115,7 @@ export const EditSurvey = () => {
name="title" name="title"
className="font-bold text-4xl text-center m-2 border-b-2" className="font-bold text-4xl text-center m-2 border-b-2"
placeholder="설문지 제목" placeholder="설문지 제목"
value={survey.title}
onChange={handleSurvey} onChange={handleSurvey}
></input> ></input>
<input <input
...@@ -121,6 +124,7 @@ export const EditSurvey = () => { ...@@ -121,6 +124,7 @@ export const EditSurvey = () => {
className="font-bold text-1xl text-center m-2 resize-none" className="font-bold text-1xl text-center m-2 resize-none"
placeholder="설문조사에 대한 설명을 입력해주세요" placeholder="설문조사에 대한 설명을 입력해주세요"
size={50} size={50}
value={survey.comment}
onChange={handleSurvey} onChange={handleSurvey}
></input> ></input>
</div> </div>
...@@ -143,7 +147,7 @@ export const EditSurvey = () => { ...@@ -143,7 +147,7 @@ export const EditSurvey = () => {
type="submit" type="submit"
className="border bg-themeColor my-5 py-2 px-3 font-bold text-white" className="border bg-themeColor my-5 py-2 px-3 font-bold text-white"
> >
설문조사 생성 저장하기
</button> </button>
</div> </div>
</div> </div>
......
// import React, { FormEvent, useEffect, useState } from "react";
// import { useParams, useNavigate } from "react-router-dom";
// import { questionApi, surveyApi } from "../apis";
// import { SpinnerIcon } from "../icons";
// import { Question } from "../questions";
// import { BasicQuestionType, SurveyType } from "../types";
// import { catchErrors } from "../helpers";
// export const EditSurvey = () => {
// let { surveyId } = useParams<{ surveyId: string }>();
// const navigate = useNavigate();
// useEffect(() => {
// getSurvey();
// }, [surveyId]);
// const [error, setError] = useState("");
// const [loading, setLoading] = useState(false);
// const [success, setSuccess] = useState(false);
// const [survey, setSurvey] = useState<SurveyType>({
// _id: surveyId,
// user: {},
// title: "",
// comment: "",
// questions: [],
// });
// const [currentId, setCurrentId] = useState("");
// const changeCurrentId = (id: string) => {
// setCurrentId(id);
// };
// async function getSurvey() {
// try {
// if (surveyId) {
// const thisSurvey: SurveyType = await surveyApi.getSurvey(surveyId);
// setSurvey(thisSurvey);
// setSuccess(true);
// setError("");
// } else {
// setLoading(true);
// }
// } catch (error) {
// catchErrors(error, setError);
// // navigate(`/`, {
// // replace: false,
// // });
// } finally {
// setLoading(false);
// }
// }
// const handleQuestion = (id: string) => {
// const newList: BasicQuestionType[] = [...survey.questions];
// setSurvey({ ...survey, questions: newList });
// };
// const handleSurvey = (event: React.ChangeEvent<HTMLInputElement>) => {
// const { name, value } = event.currentTarget;
// setSurvey({ ...survey, [name]: value });
// };
// async function handleSubmit(event: FormEvent) {
// event.preventDefault();
// try {
// const newSurvey: SurveyType = await surveyApi.editSurvey(survey);
// console.log(newSurvey);
// setSuccess(true);
// setError("");
// } catch (error) {
// catchErrors(error, setError);
// } finally {
// setLoading(false);
// }
// }
// const questions = survey.questions;
// console.log(questions);
// return (
// <>
// {error ? alert(error) : <></>}
// {loading && (
// <SpinnerIcon className="animate-spin h-5 w-5 mr-1 text-slate" />
// )}
// <form onSubmit={handleSubmit}>
// <div className="flex flex-col place-items-center">
// <div className="flex flex-col container place-items-center mt-4">
// <input
// type="text"
// name="title"
// className="font-bold text-4xl text-center m-2 border-b-2"
// placeholder="설문지 제목"
// value={survey.title}
// onChange={handleSurvey}
// ></input>
// <input
// type="text"
// name="comment"
// className="font-bold text-1xl text-center m-2 resize-none"
// placeholder="설문조사에 대한 설명을 입력해주세요"
// size={50}
// value={survey.comment}
// onChange={handleSurvey}
// ></input>
// </div>
// {questions.map((question) => (
// <Question
// element={question}
// currentId={currentId}
// />
// ))}
// <div className="flex w-4/5 content-center justify-center border-2 border-black h-8 mt-3">
// 질문 추가
// </button>
// </div>
// <div>
// <button
// type="submit"
// className="border bg-themeColor my-5 py-2 px-3 font-bold text-white"
// >
// 저장하기
// </button>
// </div>
// </div>
// </form>
// </>
// );
// };
...@@ -16,6 +16,8 @@ export interface SurveyType { ...@@ -16,6 +16,8 @@ export interface SurveyType {
title: string; title: string;
comment: string; comment: string;
questions: BasicQuestionType[]; questions: BasicQuestionType[];
createdAt?: string;
updatedAt?: string;
} }
export interface BasicQuestionType { export interface BasicQuestionType {
......
...@@ -41,10 +41,11 @@ export const userByQuestionId = async ( ...@@ -41,10 +41,11 @@ export const userByQuestionId = async (
const req = reqExp as TypedRequestAuth<{ userId: string }>; const req = reqExp as TypedRequestAuth<{ userId: string }>;
let user = await questionDb.findUserByQuestionId(questionId); let user = await questionDb.findUserByQuestionId(questionId);
if (!user) { if (!user) {
return res.status(404).send("사용자를 찾을 수 없습니다"); return res.status(404).send("올바른 접근이 아닙니다");
} else {
req.user = user;
next();
} }
req.user = user;
next();
} catch (error: any) { } catch (error: any) {
return res return res
.status(500) .status(500)
......
...@@ -8,7 +8,7 @@ export interface TypedRequestAuth<T> extends Request { ...@@ -8,7 +8,7 @@ export interface TypedRequestAuth<T> extends Request {
} }
export const createSurvey = asyncWrap( export const createSurvey = asyncWrap(
async (reqExp: Request, res: Response, next: NextFunction) => { async (reqExp: Request, res: Response) => {
const req = reqExp as TypedRequestAuth<{ userId: string }>; const req = reqExp as TypedRequestAuth<{ userId: string }>;
const { userId } = req.auth; const { userId } = req.auth;
let survey = req.body; let survey = req.body;
...@@ -21,17 +21,31 @@ export const createSurvey = asyncWrap( ...@@ -21,17 +21,31 @@ export const createSurvey = asyncWrap(
export const getSurveyById = asyncWrap(async (req, res) => { export const getSurveyById = asyncWrap(async (req, res) => {
const { surveyId } = req.params; const { surveyId } = req.params;
const survey = await surveyDb.getSurveyById(surveyId); const survey: any = await surveyDb.getSurveyById(surveyId);
console.log("Get완료", survey); console.log("Get완료", survey);
return res.json(survey); return res.json(survey);
}); });
//동혁
export const getSurveys = asyncWrap(async (reqExp: Request, res: Response) => {
const req = reqExp as TypedRequestAuth<{ userId: string }>;
const { userId } = req.auth;
const surveys = await surveyDb.getSurveys(userId);
return res.json(surveys);
});
export const updateSurvey = asyncWrap(async (req, res) => { export const updateSurvey = asyncWrap(async (req, res) => {
const survey = req.body; const survey = req.body;
const newSurvey = await surveyDb.updateSurvey(survey); const newSurvey = await surveyDb.updateSurvey(survey);
return res.json(newSurvey); return res.json(newSurvey);
}); });
export const deleteSurvey = asyncWrap(async (req, res) => {
const { surveyId } = req.params;
const survey = await surveyDb.deleteSurvey(surveyId);
return res.json(survey);
});
export const userBySurveyId = async ( export const userBySurveyId = async (
reqExp: Request, reqExp: Request,
res: Response, res: Response,
...@@ -42,10 +56,11 @@ export const userBySurveyId = async ( ...@@ -42,10 +56,11 @@ export const userBySurveyId = async (
const req = reqExp as TypedRequestAuth<{ userId: string }>; const req = reqExp as TypedRequestAuth<{ userId: string }>;
let user = await surveyDb.findUserBySurveyId(surveyId); let user = await surveyDb.findUserBySurveyId(surveyId);
if (!user) { if (!user) {
return res.status(404).send("사용자를 찾을 수 없습니다"); return res.status(404).send("올바른 접근이 아닙니다.");
} else {
req.user = user;
next();
} }
req.user = user;
next();
} catch (error: any) { } catch (error: any) {
return res return res
.status(500) .status(500)
......
...@@ -21,7 +21,18 @@ export const getSurveyById = async (surveyId: string) => { ...@@ -21,7 +21,18 @@ export const getSurveyById = async (surveyId: string) => {
return survey; return survey;
}; };
export const getSurveys = async (userId: string) => {
const surveys = await Survey.find({ user: userId });
return surveys;
};
export const updateSurvey = async (survey: ISurvey) => { export const updateSurvey = async (survey: ISurvey) => {
const newSurvey = await Survey.findOneAndUpdate({ _id: survey._id }, survey); const newSurvey = await Survey.findOneAndUpdate({ _id: survey._id }, survey);
return newSurvey; return newSurvey;
}; };
export const deleteSurvey = async (surveyId: string) => {
console.log("survey id", surveyId);
const survey = await Survey.findOneAndDelete({ _id: surveyId });
return survey;
};
import { model, Schema, Types } from "mongoose"; import { model, Schema, Types } from "mongoose";
import { Question } from ".";
export interface ISurvey { export interface ISurvey {
_id?: Types.ObjectId; _id?: Types.ObjectId;
...@@ -8,11 +9,25 @@ export interface ISurvey { ...@@ -8,11 +9,25 @@ export interface ISurvey {
questions: Types.ObjectId[]; questions: Types.ObjectId[];
} }
const schema = new Schema<ISurvey>({ const schema = new Schema<ISurvey>(
title: { type: String }, {
comment: { type: String }, title: { type: String },
user: { type: Schema.Types.ObjectId, ref: "User" }, comment: { type: String },
questions: [{ type: Schema.Types.ObjectId, ref: "Question" }], user: { type: Schema.Types.ObjectId, ref: "User" },
}); questions: [{ type: Schema.Types.ObjectId, ref: "Question" }],
},
{ timestamps: true }
);
schema.pre(
"findOneAndDelete",
{ document: false, query: true },
async function (next) {
const doc = await this.model.findOne(this.getFilter());
const questions = doc.questions;
await Question.deleteMany({ _id: { $in: questions } });
next();
}
);
export default model<ISurvey>("Survey", schema); export default model<ISurvey>("Survey", schema);
...@@ -3,11 +3,19 @@ import { authCtrl, surveyCtrl } from "../controllers"; ...@@ -3,11 +3,19 @@ import { authCtrl, surveyCtrl } from "../controllers";
const router = express.Router(); const router = express.Router();
router.route("/").get(authCtrl.requireLogin, surveyCtrl.getSurveys);
router.route("/create").post(authCtrl.requireLogin, surveyCtrl.createSurvey); router.route("/create").post(authCtrl.requireLogin, surveyCtrl.createSurvey);
router router
.route("/edit/:surveyId") .route("/edit/:surveyId")
.get(authCtrl.requireLogin, authCtrl.authenticate, surveyCtrl.getSurveyById) .get(authCtrl.requireLogin, authCtrl.authenticate, surveyCtrl.getSurveyById)
.put(authCtrl.requireLogin, authCtrl.authenticate, surveyCtrl.updateSurvey); .put(authCtrl.requireLogin, authCtrl.authenticate, surveyCtrl.updateSurvey);
router
.route("/delete/:surveyId")
.delete(
authCtrl.requireLogin,
authCtrl.authenticate,
surveyCtrl.deleteSurvey
);
router.param("surveyId", surveyCtrl.userBySurveyId); router.param("surveyId", surveyCtrl.userBySurveyId);
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment