Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. exports.findOneAndCurrent = (req, res) => {
  2. // First, get which student to base the query on
  3. const studentId = req.user.studentId
  4. ? req.user.studentId
  5. : req.query.student
  6. ? req.query.student
  7. : null;
  8.  
  9. if (studentId === null) {
  10. res.status(404).json({
  11. success: false,
  12. msg: "No student_id provided!"
  13. });
  14. }
  15.  
  16. Task.findOne({
  17. where: {
  18. student_id: studentId,
  19. unit_id: req.params.id,
  20. is_active: true
  21. },
  22. include: [{
  23. model: Unit,
  24. where: {
  25. id: req.params.id,
  26. is_active: true
  27. },
  28. include: [{
  29. model: Question,
  30. as: 'questions',
  31. where: {
  32. unit_id: req.params.id,
  33. is_active: true
  34. },
  35. order: [['id', 'ASC']],
  36. required: false
  37. }]
  38. }],
  39. required: true
  40. })
  41. .then(task => {
  42. if (task === null) {
  43. res.status(400).json({
  44. success: false,
  45. msg: "This student is not assigned a task with this unit!"
  46. });
  47. }
  48.  
  49. const questionIds = task.Unit.questions.map(question => question.id);
  50. Activity.findAll({
  51. where: {
  52. question_id: { [Op.or]: [questionIds] },
  53. student_id: studentId,
  54. finish_time: {
  55. [Op.ne]: null
  56. }
  57. },
  58. order: [['question_id', 'ASC' ]]
  59. })
  60. .then(activities => {
  61. let questionIdsCopy = questionIds;
  62. activities.forEach(activity => {
  63. const index = questionIdsCopy.indexOf(activity.question_id);
  64. if (index > -1) questionIdsCopy.splice(index, 1);
  65. });
  66.  
  67. const current_question = questionIdsCopy.length > 0
  68. ? task.Unit.questions[questionIds.indexOf(questionIdsCopy[0])]
  69. : null;
  70.  
  71. res.json({...task.Unit.dataValues, current_question});
  72. })
  73. })
  74. .catch(err => {
  75. console.log(err);
  76. res.status(500).json({
  77. success: false,
  78. msg: "Something went wrong: " + err
  79. });
  80. });
  81. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement