/
TimurIsm
/
OpenEyes
Обзор
Документация
Войти
/
TimurIsm
/
OpenEyes
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
back/controllers/surveyController.js
137 строк
5 KB
TimurIsm
first_commit
16 май 2026, 15:34
16 май 2026, 15:34
4d3f198
Код
Авторство
О чём код?
const { Question, Answer, User } = require('../models/models'); const ApiError = require('../error/ApiError'); const { Op } = require('sequelize'); const { deepTrim } = require('../utils/stringUtils'); class SurveyController { async createQuestion(req, res, next) { try { let { text, type, answers } = req.body; text = deepTrim(text); if (!text) { return next(ApiError.badRequest('Текст вопроса не может быть пустым!')); } if (!type || !answers || answers.length === 0) { return next(ApiError.badRequest('Не все обязательные поля заполнены!')); } const cleanedAnswers = []; for (const answer of answers) { let answerText = deepTrim(answer.text); if (!answerText) { return next(ApiError.badRequest('Текст ответа не может быть пустым!')); } cleanedAnswers.push({ text: answerText }); } const question = await Question.create({ text, type, adminId: req.user.id }); const answerPromises = cleanedAnswers.map(answer => Answer.create({ text: answer.text, questionId: question.id })); await Promise.all(answerPromises); const createdQuestion = await Question.findOne({ where: { id: question.id }, include: [{ model: Answer, as: 'answers' }, { model: User, as: 'admin', attributes: ['id', 'email'] }], }); return res.json(createdQuestion); } catch (e) { return next(ApiError.internal('Ошибка при создании вопроса!')); } } async getQuestions(req, res, next) { try { const questions = await Question.findAll({ include: [{ model: Answer, as: 'answers' }] }); return res.json(questions); } catch (e) { return next(ApiError.internal('Ошибка при получении вопросов!')); } } async getQuestionById(req, res, next) { const { id } = req.params; try { const question = await Question.findOne({ where: { id }, include: [{ model: Answer, as: 'answers' }] }); if (!question) { return next(ApiError.internal('Вопрос не найден!')); } return res.json(question); } catch (e) { return next(ApiError.internal('Ошибка при получении вопроса!')); } } async deleteQuestion(req, res, next) { const { id } = req.params; try { const question = await Question.destroy({ where: { id } }); if (!question) { return next(ApiError.internal('Вопрос не найден!')); } return res.json({ message: 'Вопрос успешно удален!' }); } catch (e) { return next(ApiError.internal('Ошибка при удалении вопроса!')); } } async updateQuestion(req, res, next) { const { id } = req.params; let { text, type, answers } = req.body; try { text = deepTrim(text); if (!text) { return next(ApiError.badRequest('Текст вопроса не может быть пустым!')); } if (!type || !answers || answers.length === 0) { return next(ApiError.badRequest('Не все обязательные поля заполнены!')); } const cleanedAnswers = []; for (const answer of answers) { let answerText = deepTrim(answer.text); if (!answerText) { return next(ApiError.badRequest('Текст ответа не может быть пустым!')); } cleanedAnswers.push({ ...answer, text: answerText }); } const question = await Question.findOne({ where: { id } }); if (!question) { return next(ApiError.internal('Вопрос не найден!')); } await Question.update({ text, type }, { where: { id } }); const newAnswers = []; for (const answer of cleanedAnswers) { if (answer.id) { await Answer.update({ text: answer.text }, { where: { id: answer.id } }); } else { const newAnswer = await Answer.create({ text: answer.text, questionId: id }); newAnswers.push(newAnswer.id); } } const existingAnswerIds = cleanedAnswers.map(answer => answer.id).filter(id => id); const allAnswerIds = [...existingAnswerIds, ...newAnswers]; await Answer.destroy({ where: { questionId: id, id: { [Op.notIn]: allAnswerIds } } }); const updatedQuestion = await Question.findOne({ where: { id }, include: [{ model: Answer, as: 'answers' }], }); return res.json(updatedQuestion); } catch (e) { return next(ApiError.internal('Ошибка при обновлении вопроса!')); } } } module.exports = new SurveyController();