diff --git a/task-manager/src/index.js b/task-manager/src/index.js index 7738a69..1cacc3e 100644 --- a/task-manager/src/index.js +++ b/task-manager/src/index.js @@ -8,68 +8,76 @@ const port = process.env.PORT || 4200 app.use(express.json()) -app.post('/users', (req, res) => { +app.post('/users', async (req, res) => { const user = new User(req.body) - user.save().then(() => { + try { + await user.save() res.status(201).send(user) - }).catch((e) => { + } catch (e) { res.status(400).send(e) - }) + } }) -app.get('/users', (req, res) => { - User.find({}).then((users) => { +app.get('/users', async (req, res) => { + try { + const users = await User.find({}) res.send(users) - }).catch((e) => { + } catch (e) { res.status(500).send() - }) + } }) -app.get('/users/:id', (req, res) => { +app.get('/users/:id', async (req, res) => { const _id = req.params.id - User.findById(_id).then((user) => { + try { + const user = await User.findById(_id) + if (!user) { return res.status(404).send() } res.send(user) - }).catch((e) => { + } catch (e) { res.status(500).send() - }) + } }) -app.post('/tasks', (req, res) => { +app.post('/tasks', async (req, res) => { const task = new Task(req.body) - task.save().then(() => { + try { + await task.save() res.status(201).send(task) - }).catch((e) => { + } catch (e) { res.status(400).send(e) - }) + } }) -app.get('/tasks', (req, res) => { - Task.find({}).then((tasks) => { +app.get('/tasks', async (req, res) => { + try { + const tasks = await Task.find({}) res.send(tasks) - }).catch((e) => { + } catch (e) { res.status(500).send() - }) + } }) -app.get('/tasks/:id', (req, res) => { +app.get('/tasks/:id', async (req, res) => { const _id = req.params.id - Task.findById(_id).then((task) => { + try { + const task = await Task.findById(_id) + if (!task) { return res.status(404).send() } res.send(task) - }).catch((e) => { + } catch (e) { res.status(500).send() - }) + } }) app.listen(port, () => {