const { Router } = require('express') const { expressjwt } = require('express-jwt') const { getAnswer } = require('../../utils/common') const { ListModel } = require('./model/todo/list') const { ItemModel } = require('./model/todo/item') const { TOKEN_KEY } = require('./const') const { requiredValidate } = require('./utils') const router = Router() router.use(expressjwt({ secret: TOKEN_KEY, algorithms: ['HS256'] })) router.post('/', requiredValidate('title'), async (req, res) => { const { title } = req.body const userId = req.auth.id const list = await ListModel.create({ title, createdBy: userId }) res.send(getAnswer(null, list)) }) router.get('/list', async (req, res) => { const items = await ListModel .find({}) .populate('items') .exec() res.send(getAnswer(null, items)) }) 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() res.send(getAnswer(null, item)) }) 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)) }) module.exports = router