Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions part3/example/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
const express = require("express")
const app = express()

app.use(express.json())

let notes = [
{
id: 1,
content: "HTML is easy",
important: true
},
{
id: 2,
content: "Browser can execute only JavaScript",
important: false
},
{
id: 3,
content: "GET and POST are the most important methods of HTTP protocol",
important: true
}
]

app.get('/', (req, res) => {
res.send('<h1>Hello World!</h1>')
})

app.get('/api/notes', (req, res) => {
res.json(notes)
})

app.get('/api/notes/:id', (request, response) => {
const id = parseInt(request.params.id)
if (Number.isNaN(id)) {
response.status(402).send("Bad Request")
return
}
const note = notes.find(note => note.id === id)
if (!note) {
response.status(404).send("Not Found")
return
}
response.json(note)
})

app.delete('/api/notes/:id', (request, response) => {
const id = Number(request.params.id)
notes = notes.filter(note => note.id !== id)

response.status(204).end()
})

const generateId = () => {
const maxId = notes.length > 0
? Math.max(...notes.map(n => n.id))
: 0
return maxId + 1
}

app.post('/api/notes', (request, response) => {
const body = request.body

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

const note = {
content: body.content,
important: body.important || false,
id: generateId(),
}

notes = notes.concat(note)

response.json(note)
})

const PORT = 3001
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})
Loading