todo.controller.js 5.36 KB
Newer Older
1
import { Todo } from '../db/index.js';
Kim, Subin's avatar
Kim, Subin committed
2
import sequelize from 'sequelize';
3

Kim, Subin's avatar
Kim, Subin committed
4
const { Op } = sequelize
5

Kim, Subin's avatar
Kim, Subin committed
6
const findbyDate = async (req, res) => {
Kim, Subin's avatar
Kim, Subin committed
7
  try {
Kim, Subin's avatar
Kim, Subin committed
8
9
    // Todo 페이지
    console.log("Todo 페이지에서의 요청 처리")
Kim, Subin's avatar
Kim, Subin committed
10
11
    const userId = req.userId
    const { date } = req.query
Kim, Subin's avatar
Kim, Subin committed
12
13
14
15
    const nonCheck = await Todo.findAll({ where: { [Op.and]: [{ done: false }, { date: { [Op.eq]: date } }, { userId: userId }] }, attributes: ['id', ['title', 'todoTitle'], ['date', 'todoDate'], 'done'], order: [['updatedAt', "DESC"]] })
    const check = await Todo.findAll({ where: { [Op.and]: [{ done: true }, { date: { [Op.eq]: date } }, { userId: userId }] }, attributes: ['id', ['title', 'todoTitle'], ['date', 'todoDate'], 'done'], order: [['updatedAt', "DESC"]] })
    check.forEach(el => nonCheck.push(el.dataValues))
    return res.json(nonCheck)
Kim, Subin's avatar
Kim, Subin committed
16
17
18
19
20
  } catch (error) {
    return res.status(500).send(error.message || "todo 가져오는 중 에러 발생")
  }
}

Kim, Subin's avatar
Kim, Subin committed
21
22
const findforPercent = async (req, res) => {
  try {
Kim, Subin's avatar
Kim, Subin committed
23
24
    let nonCheck = null
    let check = null
Kim, Subin's avatar
Kim, Subin committed
25
26
27
    const userId = req.userId
    const { start, end } = req.query
    if (end) {
Kim, Subin's avatar
Kim, Subin committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
      // weekly percent
      nonCheck = await Todo.findAll({
        where: { [Op.and]: [{ userId: userId }, { done: false }, { date: { [Op.between]: [start, end] } }] },
        order: [['date']]
      })
      check = await Todo.findAll({
        where: { [Op.and]: [{ userId: userId }, { done: true }, { date: { [Op.between]: [start, end] } }] },
        order: [['date']]
      })
      const nonCheckCountList = countInList(nonCheck)
      let checkCountList = countInList(check)
      let percentList = nonCheckCountList.map(nonCheckEl => {
        const findIdx = checkCountList.findIndex(el => el.date === nonCheckEl.date)
        if (findIdx === -1) nonCheckEl['rate'] = 0
        else {
          nonCheckEl['rate'] = Math.round((checkCountList[findIdx].count / (nonCheckEl.count + checkCountList[findIdx].count)) * 100)
          checkCountList.splice(findIdx, 1)
        }

        return nonCheckEl
      })
      if (checkCountList.length !== 0) {
        checkCountList.forEach(el => el['rate'] = 100)
        const sendList = percentList.concat(checkCountList).sort((pre, next) => {
          if (pre.date < next.date) return -1
          else if (pre.date > next.date) return 1
          else return 0
        })
        return res.json(sendList)
      } else return res.json(percentList)
Kim, Subin's avatar
Kim, Subin committed
58
    } else {
Kim, Subin's avatar
Kim, Subin committed
59
      // Menu
Kim, Subin's avatar
Kim, Subin committed
60
      let percent = 0
Kim, Subin's avatar
Kim, Subin committed
61
62
      nonCheck = await Todo.findAndCountAll({ where: { [Op.and]: [{ date: { [Op.eq]: start } }, { userId: userId }, { done: false }] }, order: [['updatedAt', "DESC"]] })
      check = await Todo.findAndCountAll({ where: { [Op.and]: [{ date: { [Op.eq]: start } }, { userId: userId }, { done: true }] }, order: [['updatedAt', "DESC"]] })
Kim, Subin's avatar
Kim, Subin committed
63
      let total = nonCheck.count + check.count
Kim, Subin's avatar
Kim, Subin committed
64
      if (total !== 0) percent = Math.round((check.count / total) * 100)
Kim, Subin's avatar
Kim, Subin committed
65
66
67

      if (nonCheck.count < 3) check.rows.forEach(el => nonCheck.rows.push(el.dataValues))
      return res.json({ percent: percent, list: nonCheck.rows.slice(0, 3) })
Kim, Subin's avatar
Kim, Subin committed
68
69
70
71
72
73
    }
  } catch (error) {
    return res.status(500).send(error.message || "todo 가져오는 중 에러 발생")
  }
}

Kim, Subin's avatar
Kim, Subin committed
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const create = async (req, res) => {
  try {
    const userId = req.userId
    const { todoTitle, todoDate } = req.body
    const newTodo = await Todo.create({ title: todoTitle, date: todoDate, userId: userId })
    return res.json(newTodo)
  } catch (error) {
    return res.status(500).send(error.message || "todo 등록 중 에러 발생")
  }
}

const edit = async (req, res) => {
  try {
    let updated = null
    const userId = req.userId
    const { todoId } = req.query
Kim, Subin's avatar
Kim, Subin committed
90
    const { todoTitle, todoDate, done } = req.body
Kim, Subin's avatar
Kim, Subin committed
91
    if (todoTitle) updated = await Todo.update({ title: todoTitle, date: todoDate }, { where: { [Op.and]: [{ id: todoId }, { userId: userId }] } })
Kim, Subin's avatar
Kim, Subin committed
92
93
    else if (todoDate) updated = await Todo.update({ date: todoDate }, { where: { [Op.and]: [{ id: todoId }, { userId: userId }] } })
    else updated = await Todo.update({ done: !done }, { where: { [Op.and]: [{ id: todoId }, { userId: userId }] } })
Kim, Subin's avatar
Kim, Subin committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    if (!updated) throw new Error("해당 todo의 일부 정보를 수정하는데 실패하였습니다.")
    else return res.send(200)
  } catch (error) {
    return res.status(500).send(error.message || "todo 수정 중 에러 발생")
  }
}

const remove = async (req, res) => {
  try {
    const userId = req.userId
    const { todoId } = req.query
    const deleted = await Todo.destroy({ where: { [Op.and]: [{ id: todoId }, { userId: userId }] } })
    if (!deleted) throw new Error("해당 todo를 삭제하는데 실패하였습니다.")
    else return res.send(200)
  } catch (error) {
    return res.status(500).send(error.message || "todo 삭제 중 에러 발생")
  }
}

const getParams = async (req, res, next) => {
  try {
    const { userId } = req.params
    req.userId = userId
    next()
  } catch (error) {
    return res.status(500).send(error.message || "todo 가져오는 중 에러 발생")
  }
}

Kim, Subin's avatar
Kim, Subin committed
123
124
125
126
127
128
129
130
131
function countInList(list) {
  const countList = list.reduce((acc, cur) => {
    const findIdx = acc.findIndex(el => el.date === cur.dataValues.date)
    if (findIdx === -1) acc.push({ date: cur.dataValues.date, count: 1 })
    else acc[findIdx].count += 1

    return acc
  }, [])
  return countList
Kim, Subin's avatar
Kim, Subin committed
132
133
134
135
}

export default {
  findbyDate,
Kim, Subin's avatar
Kim, Subin committed
136
  findforPercent,
Kim, Subin's avatar
Kim, Subin committed
137
138
139
  create,
  edit,
  remove,
Kim, Subin's avatar
Kim, Subin committed
140
  getParams
141
}