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

68 lines
1.5 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-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 16:52:10 +03:00
router.get('/list', async (req, res) => {
const items = await ListModel
.find({})
.populate('items')
.exec()
res.send(getAnswer(null, items))
})
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
})
router.get('/:todoId', async (req, res) => {
const { todoId } = req.params
2025-01-18 17:45:16 +03:00
const list = await ListModel
.findById(todoId)
.populate('items')
.exec()
2025-01-18 17:08:09 +03:00
if (!list) {
throw new Error('list not found')
}
res.send(getAnswer(null, list))
})
2025-01-18 16:52:10 +03:00
2024-10-16 11:06:23 +03:00
module.exports = router