multy-stub/server/routers/todo/routes.js

101 lines
2.1 KiB
JavaScript
Raw Normal View History

2024-10-16 11:06:23 +03:00
const { Router } = require('express')
2025-01-18 16:50:58 +03:00
const { expressjwt } = require('express-jwt')
const { getAnswer } = require('../../utils/common')
2024-10-16 11:06:23 +03:00
2025-01-17 19:51:33 +03:00
const { ListModel } = require('./model/todo/list')
const { ItemModel } = require('./model/todo/item')
2025-01-18 16:50:58 +03:00
const { TOKEN_KEY } = require('./const')
const { requiredValidate } = require('./utils')
2024-10-16 11:06:23 +03:00
const router = Router()
2025-01-19 22:23:19 +03:00
router.get('/list', async (req, res) => {
const items = await ListModel
.find({})
.populate('items')
.exec()
res.send(getAnswer(null, items))
})
router.get('/:todoId', async (req, res) => {
const { todoId } = req.params
const list = await ListModel
.findById(todoId)
.populate('items')
.exec()
if (!list) {
throw new Error('list not found')
}
res.send(getAnswer(null, list))
})
2025-01-18 16:50:58 +03:00
router.use(expressjwt({ secret: TOKEN_KEY, algorithms: ['HS256'] }))
2024-10-16 11:06:23 +03:00
2025-01-18 16:50:58 +03:00
router.post('/', requiredValidate('title'), async (req, res) => {
const { title } = req.body
const userId = req.auth.id
2024-10-16 11:06:23 +03:00
2025-01-18 16:50:58 +03:00
const list = await ListModel.create({ title, createdBy: userId })
2024-10-16 11:06:23 +03:00
res.send(getAnswer(null, list))
})
2025-01-18 17:08:09 +03:00
router.post('/item', requiredValidate('todoId', 'title'), async (req, res) => {
const { todoId, title } = req.body
const list = await ListModel.findById(todoId)
if (!list) {
throw new Error('list not found')
}
const userId = req.auth.id
const item = await ItemModel.create({ title, createdBy: userId })
list.items.push(item)
await list.save()
2025-01-18 17:16:35 +03:00
res.send(getAnswer(null, item))
2025-01-18 17:08:09 +03:00
})
2025-01-19 22:47:47 +03:00
// closed = new Date().toISOString()
router.patch('/item/:itemId', async (req, res) => {
const { itemId } = req.params
const { title, done } = req.body
const item = await ItemModel.findById(itemId)
if (!item) {
throw new Error('item not found')
}
if (title) {
item.title = title
}
if (done) {
item.done = done
item.closed = done ? new Date().toISOString() : null
}
await item.save()
res.send(getAnswer(null, item))
})
router.delete('/item/:itemId', async (req, res) => {
const { itemId } = req.params
await ItemModel.findByIdAndDelete(itemId)
res.send(getAnswer(null, { ok: true }))
})
2025-01-18 16:52:10 +03:00
2024-10-16 11:06:23 +03:00
module.exports = router