Commit 7cfe38be authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

surveyDB

parent bf1fbd5f
import React, { useState } from "react"; import React from "react";
import { Questions } from "./Questions"; import { Page } from "./Page";
import { QuestionProvider } from "./question.context"; import { QuestionProvider } from "./question.context";
export const CreateSurveyForm = () => { export const CreateSurveyForm = () => {
const [survey, setSurvey] = useState();
const [error, setError] = useState("");
const [disabled, setDisabled] = useState(false);
const [success, setSuccess] = useState(false);
return ( return (
<> <>
<QuestionProvider> <QuestionProvider>
<div className="flex flex-col place-items-center"> <Page />
<div className="flex flex-col container place-items-center mt-4">
<input
type="text"
className="font-bold text-4xl text-center m-2 border-b-2"
placeholder="설문지 제목"
></input>
<textarea
className="font-bold text-1xl text-center m-2 resize-none"
placeholder="설문조사에 대한 설명을 입력해주세요"
rows={2}
cols={60}
></textarea>
</div>
<Questions />
<div>
<button className="border bg-themeColor my-5 py-2 px-3 font-bold text-white">
설문조사 생성
</button>
</div>
</div>
</QuestionProvider> </QuestionProvider>
</> </>
); );
......
import React from "react";
import { Questions } from "./Questions";
import { useQuestion } from "./question.context";
export const Page = () => {
const { handleSurvey, handleSubmit } = useQuestion();
return (
<>
<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="설문지 제목"
onChange={handleSurvey}
></input>
<input
type="text"
name="comment"
className="font-bold text-1xl text-center m-2 resize-none"
placeholder="설문조사에 대한 설명을 입력해주세요"
size={50}
onChange={handleSurvey}
></input>
</div>
<Questions />
<div>
<button
type="submit"
className="border bg-themeColor my-5 py-2 px-3 font-bold text-white"
>
설문조사 생성
</button>
</div>
</div>
</form>
</>
);
};
...@@ -34,7 +34,9 @@ export const Questions = ({}: Props) => { ...@@ -34,7 +34,9 @@ export const Questions = ({}: Props) => {
} }
})} })}
<div className="flex w-4/5 content-center justify-center border-2 border-black h-8 mt-3"> <div className="flex w-4/5 content-center justify-center border-2 border-black h-8 mt-3">
<button onClick={addQuestion}>질문 추가</button> <button type="button" onClick={addQuestion}>
질문 추가
</button>
</div> </div>
</> </>
); );
......
...@@ -5,32 +5,67 @@ import React, { ...@@ -5,32 +5,67 @@ import React, {
useContext, useContext,
useState, useState,
} from "react"; } from "react";
import axios from "axios"; import { BasicQuestionType, SurveyType } from "../types";
import { BasicQuestionType } from "../types"; import { questionApi, surveyApi } from "../apis";
import { questionApi } from "../apis";
interface IQuestionContext { interface IQuestionContext {
handleSurvey: (e: React.ChangeEvent<HTMLInputElement>) => void;
handleSubmit: (event: React.FormEvent<HTMLFormElement>) => void;
questionListChange: (e: React.ChangeEvent<HTMLInputElement>) => void; questionListChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
questionList: BasicQuestionType[]; questionList: BasicQuestionType[];
editClick: (e: React.MouseEvent<HTMLButtonElement>) => void; editClick: (e: React.MouseEvent<HTMLButtonElement>) => void;
editCompleteClick: (e: React.MouseEvent<HTMLButtonElement>) => void;
currentId: string; currentId: string;
addQuestion: (e: React.MouseEvent<HTMLButtonElement>) => Promise<void>; addQuestion: (e: React.MouseEvent<HTMLButtonElement>) => Promise<void>;
} }
const QuestionContext = createContext<IQuestionContext>({ const QuestionContext = createContext<IQuestionContext>({
handleSurvey: () => {},
handleSubmit: () => {},
questionListChange: () => {}, questionListChange: () => {},
questionList: [], questionList: [],
editClick: () => {}, editClick: () => {},
editCompleteClick: () => {},
currentId: "", currentId: "",
addQuestion: async () => {}, addQuestion: async () => {},
}); });
export const QuestionProvider: FC<{ children: ReactNode }> = ({ children }) => { export const QuestionProvider: FC<{ children: ReactNode }> = ({ children }) => {
const [error, setError] = useState("");
const [disabled, setDisabled] = useState(false);
const [success, setSuccess] = useState(false);
const [questionList, setQuestionList] = useState<Array<BasicQuestionType>>( const [questionList, setQuestionList] = useState<Array<BasicQuestionType>>(
[] []
); );
const [currentId, setCurrentId] = useState<string>(""); const [currentId, setCurrentId] = useState<string>("");
const [survey, setSurvey] = useState<SurveyType>({
title: "",
comment: "",
//questions 는 _id들의 배열
questions: [],
});
function handleSurvey(event: React.ChangeEvent<HTMLInputElement>) {
setSurvey({
...survey,
[event.currentTarget.name]: event.currentTarget.value,
});
}
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
try {
const newSurvey: SurveyType = await surveyApi.createSurvey(survey);
console.log(newSurvey);
// setSuccess(true);
// setError("");
} catch (error) {
console.log("에러발생");
// catchErrors(error, setError)
} finally {
// setLoading(false);
}
}
function questionListChange(e: React.ChangeEvent<HTMLInputElement>): void { function questionListChange(e: React.ChangeEvent<HTMLInputElement>): void {
const newList: BasicQuestionType[] = [...questionList]; const newList: BasicQuestionType[] = [...questionList];
const obj: any = newList.find((a) => a._id === e.target.id); //고유 _id로 질문찾기 const obj: any = newList.find((a) => a._id === e.target.id); //고유 _id로 질문찾기
...@@ -42,6 +77,7 @@ export const QuestionProvider: FC<{ children: ReactNode }> = ({ children }) => { ...@@ -42,6 +77,7 @@ export const QuestionProvider: FC<{ children: ReactNode }> = ({ children }) => {
async function addQuestion() { async function addQuestion() {
try { try {
const newQ: BasicQuestionType = await questionApi.createQuestion(); const newQ: BasicQuestionType = await questionApi.createQuestion();
setSurvey({ ...survey, questions: [...survey.questions, newQ._id] });
setQuestionList([...questionList, newQ]); setQuestionList([...questionList, newQ]);
// setSuccess(true); // setSuccess(true);
// setError(""); // setError("");
...@@ -57,13 +93,18 @@ export const QuestionProvider: FC<{ children: ReactNode }> = ({ children }) => { ...@@ -57,13 +93,18 @@ export const QuestionProvider: FC<{ children: ReactNode }> = ({ children }) => {
setCurrentId(e.currentTarget.id); setCurrentId(e.currentTarget.id);
} }
function editCompleteClick(e: React.MouseEvent<HTMLButtonElement>) {}
return ( return (
<QuestionContext.Provider <QuestionContext.Provider
value={{ value={{
handleSurvey,
handleSubmit,
questionListChange, questionListChange,
addQuestion, addQuestion,
questionList, questionList,
editClick, editClick,
editCompleteClick,
currentId, currentId,
}} }}
> >
......
import axios from "axios";
export * as authApi from "./auth.api"; export * as authApi from "./auth.api";
export * as questionApi from "./question.api" export * as questionApi from "./question.api"
export * as surveyApi from "./survey.api"
import axios from "axios"; import axios from "axios";
import { } from "../types";
import baseUrl from "./baseUrl"; import baseUrl from "./baseUrl";
export const createQuestion = async () => { export const createQuestion = async () => {
......
import axios from "axios";
import { SurveyType } from "../types";
import baseUrl from "./baseUrl";
export const createSurvey = async (survey:SurveyType) => {
console.log(survey)
const {data} = await axios.post(`${baseUrl}/surveys/create`, {...survey})
return data;
}
\ No newline at end of file
...@@ -10,6 +10,12 @@ export interface SignupUser { ...@@ -10,6 +10,12 @@ export interface SignupUser {
password: string; password: string;
} }
export interface SurveyType{
title: string;
comment: string;
questions: string[];
}
export interface BasicQuestionType { export interface BasicQuestionType {
type: string; type: string;
_id: string; _id: string;
......
export * as authCtrl from "./auth.controller"; export * as authCtrl from "./auth.controller";
export * as questionCtrl from "./question.controller"; export * as questionCtrl from "./question.controller";
export * as surveyCtrl from "./survey.controller";
export * as roleCtrl from "./role.controller"; export * as roleCtrl from "./role.controller";
export * as userCtrl from "./user.controller"; export * as userCtrl from "./user.controller";
import { surveyDb } from "../db";
import { asyncWrap } from "../helpers/asyncWrap";
export const createSurvey = asyncWrap(async (req, res) => {
const survey = req.body;
console.log("Survey body", survey);
const newSurvey = await surveyDb.createSurvey(survey);
return res.json(newSurvey);
});
export * as roleDb from "./role.db"; export * as roleDb from "./role.db";
export * as questionDb from "./question.db"; export * as questionDb from "./question.db";
export * as surveyDb from "./survey.db";
export * as userDb from "./user.db"; export * as userDb from "./user.db";
...@@ -2,13 +2,5 @@ import { Question, IQuestion } from "../models"; ...@@ -2,13 +2,5 @@ import { Question, IQuestion } from "../models";
export const createQuestion = async (question: IQuestion) => { export const createQuestion = async (question: IQuestion) => {
const newQuestion = await Question.create(question); const newQuestion = await Question.create(question);
const newQ = { return newQuestion;
_id: newQuestion._id,
type: newQuestion.type,
title: newQuestion.title,
isRequired: newQuestion.isRequired,
comment: newQuestion.comment,
content: newQuestion.content,
}
return newQ;
}; };
import { Survey, ISurvey } from "../models";
export const createSurvey = async (survey: ISurvey) => {
const newSurvey = await Survey.create(survey);
return newSurvey;
};
export { default as Question, IQuestion } from "./question.model"; export { default as Question, IQuestion } from "./question.model";
export { default as Survey, ISurvey } from "./survey.model";
export { default as Role } from "./role.model"; export { default as Role } from "./role.model";
export { default as User, IUser } from "./user.model"; export { default as User, IUser } from "./user.model";
...@@ -10,13 +10,14 @@ export interface IQuestion { ...@@ -10,13 +10,14 @@ export interface IQuestion {
} }
const schema = new Schema<IQuestion>({ const schema = new Schema<IQuestion>({
// id: {type:String},
type:{type:String}, type:{type:String},
title: {type:String}, title: {type:String},
isRequired: {type:Boolean}, isRequired: {type:Boolean},
comment:{type: String}, comment:{type: String},
content:{type: Object}, content:{type: Object},
}); }, {toJSON: {
versionKey: false
}});
export default model<IQuestion>("Question", schema); export default model<IQuestion>("Question", schema);
\ No newline at end of file
import { model, Schema, Types } from "mongoose";
export interface ISurvey {
title: string;
comment: string;
questions: Types.ObjectId[]
}
const schema = new Schema<ISurvey>({
title: {type:String},
comment: {type:String},
questions: [{ type: Schema.Types.ObjectId, ref: 'Question' }],
});
export default model<ISurvey>("Survey", schema);
\ No newline at end of file
import express from "express"; import express from "express";
import authRouter from "./auth.route"; import authRouter from "./auth.route";
import questionRouter from "./question.route"; import questionRouter from "./question.route";
import surveyRouter from "./survey.route";
import roleRouter from "./role.route"; import roleRouter from "./role.route";
import userRouter from "./user.route"; import userRouter from "./user.route";
...@@ -8,6 +9,7 @@ const router = express.Router(); ...@@ -8,6 +9,7 @@ const router = express.Router();
router.use("/auth", authRouter); router.use("/auth", authRouter);
router.use("/questions", questionRouter); router.use("/questions", questionRouter);
router.use("/surveys", surveyRouter);
router.use("/roles", roleRouter); router.use("/roles", roleRouter);
router.use("/users", userRouter); router.use("/users", userRouter);
......
import express from "express";
import { surveyCtrl } from "../controllers";
const router = express.Router();
router
.route("/create")
.post(surveyCtrl.createSurvey);
export default router;
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