54 lines
1.4 KiB
JavaScript
54 lines
1.4 KiB
JavaScript
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')))
|
|
}
|
|
|
|
res.send(getAnswer(null, item.comments))
|
|
})
|
|
|
|
module.exports = router
|