Skip to content
Open
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
21 changes: 21 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"cors": "^2.8.5",
"express": "^4.18.2",
"morgan": "^1.10.0",
"node": "^20.15.0",
"nodemon": "^3.0.1"
},
"devDependencies": {
Expand Down
60 changes: 60 additions & 0 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,65 @@ app.use(express.json())

// write your app code here

let contacts = [
{id: 1, firstName: 'John', lastName: 'Carmack'},
{id: 2, firstName: 'Grace', lastName: 'Hopper'},

]
let nextId = 3

//gets all contacts
app.get('/contacts', (request, respond) => {
respond.status(200).json({ contacts })
})

// gets a contact by Id
app.get('/contacts/:id', (request, respond) => {
const id = parseInt(request.params.id)
const contact = contacts.find(c => c.id === id)
if (contact) {
respond.status(200).json({ contact })
} else {
//respond.status(404).send('Contact not found')
respond.status(404).json({ message: 'contact not found' })
}
})

//create a new contact
app.post('/contacts', (request, respond) => {
const newContact = request.body
newContact.id = nextId++
contacts.push(newContact)
respond.status(201).json({ contact: newContact })

})

// edit and update a contact
app.put('/contacts/:id', (request, respond) => {
const id = parseInt(request.params.id)
const index = contacts.findIndex (c => c.id === id)
if (index !== -1) {
contacts[index] = {...contacts[index], ...request.body}
const updatedContact = contacts[index]
respond.status(200).json({contact: updatedContact})
} else {
respond.status(404).json('Message: Contacts not found')
}

})


//then delete a contact
app.delete('/contacts/:id', (request, respond) => {
const id = parseInt(request.params.id)
const index = contacts.findIndex(c => c.id === id)
if (index !== -1) {
const deletedContact = contacts.splice(index, 1)
respond.status(200).json ({ contact: deletedContact[0] })
} else {
respond.status(404).json('Message: contacts not found')
}
})


module.exports = app