Skip to content

Commit

Permalink
add update and delete endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
marekzelinka committed Jul 23, 2024
1 parent 8b2e1c9 commit 5ff44de
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 19 deletions.
9 changes: 9 additions & 0 deletions api.rest
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,14 @@ Content-Type: application/json
"content": "node.js is also cool"
}

### Update note
PUT http://localhost:3000/api/notes/669fad878eab5fa0dcdfd8d0
Content-Type: application/json

{
"content": "React is cool",
"important": true
}

### Test unknown endpoint
GET http://localhost:3000/not/found
73 changes: 54 additions & 19 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,19 @@ async function run() {
res.send('<h1>Hello World!</h1>')
})

app.get('/api/notes', async (_req, res) => {
const notes = await Note.find()
res.json(notes)
app.get('/api/notes', async (_req, res, next) => {
try {
const notes = await Note.find()
res.json(notes)
} catch (error) {
next(error)
}
})

app.get('/api/notes/:id', async (req, res, next) => {
try {
const noteId = req.params.id
const note = await Note.findById(noteId)
const id = req.params.id
const note = await Note.findById(id)

if (!note) {
return res.status(404).end()
Expand All @@ -46,27 +50,58 @@ async function run() {
}
})

app.delete('/api/notes/:id', async (req, res) => {
const noteId = req.params.id
await Note.findByIdAndDelete(noteId)
app.delete('/api/notes/:id', async (req, res, next) => {
try {
const id = req.params.id
await Note.findByIdAndDelete(id)

res.status(204).end()
res.status(204).end()
} catch (error) {
next(error)
}
})

app.post('/api/notes', async (req, res) => {
const { content, important } = req.body
app.post('/api/notes', async (req, res, next) => {
try {
const { content, important } = req.body

if (!content) {
return res.status(400).json({ error: 'content missing' })
}

const note = new Note({
content,
important: Boolean(important) || false,
})
const savedNote = await note.save()

if (!content) {
return res.status(400).json({ error: 'content missing' })
res.status(201).json(savedNote)
} catch (error) {
next(error)
}
})

const note = new Note({
content,
important: Boolean(important) || false,
})
const savedNote = await note.save()
app.put('/api/notes/:id', async (req, res, next) => {
try {
const id = req.params.id
const { content, important } = req.body

if (!content) {
return res.status(400).json({ error: 'content missing' })
}

res.status(201).json(savedNote)
const updates = {
content,
important: Boolean(important) || false,
}
const updatedNote = await Note.findByIdAndUpdate(id, updates, {
new: true,
})

res.json(updatedNote)
} catch (error) {
next(error)
}
})

app.use(unknownEndpoint)
Expand Down

0 comments on commit 5ff44de

Please sign in to comment.