multy-stub/server/routers/todo/routes.js
Primakov Alexandr Alexandrovich afc782f50f check
2024-10-16 11:15:18 +03:00

50 lines
1.2 KiB
JavaScript

const { Router } = require('express')
const { ListModel } = require('../../data/model/todo/list')
const { ItemModel } = require('../../data/model/todo/item')
const { getAnswer } = require('../../utils/common')
const router = Router()
// test - http://localhost:8033/todo/list
router.get('/list', async (req, res) => {
const items = await ListModel
.find({})
.populate('items')
.exec()
res.send(getAnswer(null, items))
})
// test - http://localhost:8033/todo/list/create/new%20List%20Name
router.get('/list/create/:title', async (req, res) => {
const { title } = req.params
const list = await ListModel.create({ title })
res.send(getAnswer(null, list))
})
// test - http://localhost:8033/todo/item/create/:listId/new%20one
router.get('/item/create/:listId/:name', async (req, res, next) => {
const { name, listId } = req.params
try {
const list = await ListModel.findById(listId)
if (!list) {
throw new Error('no such list')
}
const item = await ItemModel.create({ name })
list.addItem(item.id)
res.send(getAnswer(null, await ListModel.findById(listId)))
} catch (error) {
next(error)
}
})
module.exports = router