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

54 lines
1.4 KiB
JavaScript
Raw Normal View History

2025-01-18 17:45:16 +03:00
const { Router } = require('express')
const { expressjwt } = require('express-jwt')
const { getAnswer } = require('../../utils/common')
const { CommentModel } = require('./model/todo/comment')
const { ListModel } = require('./model/todo/list')
const { ItemModel } = require('./model/todo/item')
const { TOKEN_KEY } = require('./const')
const router = Router()
router.use(expressjwt({ secret: TOKEN_KEY, algorithms: ['HS256'] }))
router.post('/:todoId/:itemId', async (req, res) => {
const { text } = req.body
const { todoId, itemId } = req.params
const todo = await ListModel.findById(todoId)
if (!todo) {
return res.send(getAnswer(new Error('no such todo')))
}
const item = await ItemModel.findById(itemId)
if (!item) {
return res.send(getAnswer(new Error('no such item')))
}
const userId = req.auth.id
const comment = await CommentModel.create({ text, author: userId, createdBy: userId })
await item.addComment(comment.id)
res.send(getAnswer(null, comment))
})
router.get('/:todoId/:itemId', async (req, res) => {
const { todoId, itemId } = req.params
const todo = await ListModel.findById(todoId)
if (!todo) {
return res.send(getAnswer(new Error('no such todo')))
}
const item = await ItemModel.findById(itemId).populate('comments').exec()
if (!item) {
return res.send(getAnswer(new Error('no such item')))
}
2025-01-19 20:44:26 +03:00
res.send(getAnswer(null, item))
2025-01-18 17:45:16 +03:00
})
module.exports = router