Skip to content

Commit

Permalink
use db in routes
Browse files Browse the repository at this point in the history
  • Loading branch information
marekzelinka committed Jul 23, 2024
1 parent 2bc7cac commit f5265af
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 40 deletions.
6 changes: 3 additions & 3 deletions api.rest
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ GET http://localhost:3000
GET http://localhost:3000/api/notes

### Get single note
GET http://localhost:3000/api/notes/4
GET http://localhost:3000/api/notes/669fb91dd2a9ba472da74ee8

### Get single nonexisting note
GET http://localhost:3000/api/notes/nonexistingid
GET http://localhost:3000/api/notes/669fb91dd2a9ba472da74ee7

### Delete note
DELETE http://localhost:3000/api/notes/1
DELETE http://localhost:3000/api/notes/669fab9669330fe1799ecd72

### Create note
POST http://localhost:3000/api/notes
Expand Down
49 changes: 12 additions & 37 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,6 @@ const MONGODB_URI = process.env.MONGODB_URI

let app = express()

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,
},
]

function generateNoteId() {
let maxId = notes.length
? Math.max(...notes.map((note) => Number(note.id)))
: 0
return String(maxId + 1)
}

run().catch(console.dir)

async function run() {
Expand All @@ -56,9 +31,9 @@ async function run() {
res.json(notes)
})

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

if (!note) {
return res.status(404).end()
Expand All @@ -67,26 +42,26 @@ async function run() {
res.json(note)
})

app.delete('/api/notes/:id', (req, res) => {
let id = req.params.id
notes = notes.filter((note) => note.id !== id)
app.delete('/api/notes/:id', async (req, res) => {
let noteId = req.params.id
await Note.findByIdAndDelete(noteId)
res.status(204).end()
})

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

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

let note = {
let note = new Note({
content,
important: Boolean(important) || false,
id: generateNoteId(),
}
notes = notes.concat(note)
res.status(201).json(note)
})
let savedNote = await note.save()

res.status(201).json(savedNote)
})

app.use(unknownEndpoint)
Expand Down

0 comments on commit f5265af

Please sign in to comment.