Skip to content
Open

Tom #82

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
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

const app = require('./server.js')
const port = 3030

Expand Down
66 changes: 57 additions & 9 deletions src/server.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,61 @@
const express = require("express")
const morgan = require("morgan")
const cors = require("cors")
const app = express()
const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const contactsData = require('../data/contacts');

app.use(morgan("dev"))
app.use(cors())
app.use(express.json())
const app = express();

// write your app code here

app.use(morgan('dev'));
app.use(cors());
app.use(express.json());

module.exports = app
app.get('/contacts', (req, res) => {
res.status(200).json({ contacts: contactsData });
});


app.get('/contacts/:id', (req, res) => {
const { id } = req.params;
const contact = contactsData.find((contact) => contact.id === parseInt(id));
if (!contact) {
res.status(404).json({ message: 'Contact not found' });
} else {
res.status(200).json({ contact });
}
});

app.post('/contacts', (req, res) => {
const newContact = req.body;
newContact.id = contactsData.length + 1;
contactsData.push(newContact);
res.status(201).json({ contact: newContact });
});


app.put('/contacts/:id', (req, res) => {
const { id } = req.params;
const updatedContact = req.body;
const index = contactsData.findIndex((contact) => contact.id === parseInt(id));
if (index === -1) {
res.status(404).json({ message: 'Contact not found' });
} else {
contactsData[index] = { ...contactsData[index], ...updatedContact };
res.status(200).json({ contact: contactsData[index] });
}
});


app.delete('/contacts/:id', (req, res) => {
const { id } = req.params;
const index = contactsData.findIndex((contact) => contact.id === parseInt(id));
if (index === -1) {
res.status(404).json({ message: 'Contact not found' });
} else {
const deletedContact = contactsData.splice(index, 1);
res.status(200).json({ contact: deletedContact[0] });
}
});


module.exports = app;