Video 115: Authenticating Task Endpoints
This commit is contained in:
parent
771e9bd0d4
commit
3a9e40b2f1
@ -17,20 +17,20 @@ router.post('/tasks', auth, async (req, res) => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
router.get('/tasks', async (req, res) => {
|
router.get('/tasks', auth, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const tasks = await Task.find({})
|
await req.user.populate('tasks').execPopulate()
|
||||||
res.send(tasks)
|
res.send(req.user.tasks)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
res.status(500).send()
|
res.status(500).send()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
router.get('/tasks/:id', async (req, res) => {
|
router.get('/tasks/:id', auth, async (req, res) => {
|
||||||
const _id = req.params.id
|
const _id = req.params.id
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const task = await Task.findById(_id)
|
const task = await Task.findOne({ _id, owner: req.user._id })
|
||||||
|
|
||||||
if (!task) {
|
if (!task) {
|
||||||
return res.status(404).send()
|
return res.status(404).send()
|
||||||
@ -42,7 +42,7 @@ router.get('/tasks/:id', async (req, res) => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
router.patch('/tasks/:id', async (req, res) => {
|
router.patch('/tasks/:id', auth, async (req, res) => {
|
||||||
const updates = Object.keys(req.body)
|
const updates = Object.keys(req.body)
|
||||||
const allowedUpdates = ['description', 'completed']
|
const allowedUpdates = ['description', 'completed']
|
||||||
const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
|
const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
|
||||||
@ -52,25 +52,24 @@ router.patch('/tasks/:id', async (req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const task = await Task.findById(req.params.id)
|
const task = await Task.findOne({ _id: req.params.id, owner: req.user._id })
|
||||||
|
|
||||||
updates.forEach((update) => task[update] = req.body[update])
|
|
||||||
await task.save()
|
|
||||||
|
|
||||||
|
|
||||||
if (!task) {
|
if (!task) {
|
||||||
return res.status(404).send()
|
return res.status(404).send()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
updates.forEach((update) => task[update] = req.body[update])
|
||||||
|
await task.save()
|
||||||
|
|
||||||
res.send(task)
|
res.send(task)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
res.status(400).send(e)
|
res.status(400).send(e)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
router.delete('/tasks/:id', async (req, res) => {
|
router.delete('/tasks/:id', auth, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const task = await Task.findByIdAndDelete(req.params.id)
|
const task = await Task.findOneAndDelete({ _id: req.params.id, owner: req.user._id })
|
||||||
|
|
||||||
if (!task) {
|
if (!task) {
|
||||||
return res.status(404).send()
|
return res.status(404).send()
|
||||||
|
Loading…
Reference in New Issue
Block a user