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
35 changes: 14 additions & 21 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
const express = require('express')
const logger = require('morgan')
const cors = require('cors')
const express = require("express");
const cors = require("cors");
const contactsRouter = require("./routes/api/contacts");

const contactsRouter = require('./routes/api/contacts')
const app = express();

const app = express()
app.use(cors());
app.use(express.json()); // Middleware pentru a procesa JSON în cererile HTTP

const formatsLogger = app.get('env') === 'development' ? 'dev' : 'short'
// Rutele contactelor
app.use((req, res, next) => {
console.log(`Request received: ${req.method} ${req.url}`);
next();
});

app.use("/api/contacts", contactsRouter);

app.use(logger(formatsLogger))
app.use(cors())
app.use(express.json())

app.use('/api/contacts', contactsRouter)

app.use((req, res) => {
res.status(404).json({ message: 'Not found' })
})

app.use((err, req, res, next) => {
res.status(500).json({ message: err.message })
})

module.exports = app
module.exports = app;
58 changes: 51 additions & 7 deletions models/contacts.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,63 @@
// const fs = require('fs/promises')
const fs = require('fs/promises')
const path = require('path')

const listContacts = async () => {}
const contactsPath = path.join(__dirname, 'contacts.json')
console.log('Contacts path:', contactsPath);
const listContacts = async () => {
try {
const data = await fs.readFile(contactsPath, 'utf-8');
console.log('Data read from file:', data); // Adăugați acest log pentru a verifica ce este citit
return JSON.parse(data); // Încercați să parsezi JSON-ul
} catch (error) {
console.error('Error reading contacts:', error);
if (error.code === 'ENOENT') {
return [];
}
throw error;
}
};

const getContactById = async (contactId) => {}
const getContactById = async (contactId) => {
const contacts = await listContacts()
return contacts.find(contact => contact.id === contactId)
}

const removeContact = async (contactId) => {
const contacts = await listContacts()
const index = contacts.findIndex(contact => contact.id === contactId)
if (index === -1) return null

const [deletedContact] = contacts.splice(index, 1)
await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2))
return deletedContact
}

const removeContact = async (contactId) => {}
const addContact = async (body) => {
const contacts = await listContacts()
const newContact = { ...body, id: generateId() }
contacts.push(newContact)
await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2))
return newContact
}

const updateContact = async (contactId, body) => {
const contacts = await listContacts()
const contact = contacts.find(contact => contact.id === contactId)
if (!contact) return null

const addContact = async (body) => {}
Object.assign(contact, body)
await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2))
return contact
}

const updateContact = async (contactId, body) => {}
const generateId = () => {
return Math.random().toString(36).substr(2, 9) // Basic random ID generator
}

module.exports = {
listContacts,
getContactById,
removeContact,
addContact,
updateContact,
updateContact
}
2 changes: 1 addition & 1 deletion models/contacts.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,4 @@
"email": "Donec.elementum@scelerisquescelerisquedui.net",
"phone": "(748) 206-2688"
}
]
]
112 changes: 111 additions & 1 deletion package-lock.json

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

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
"cors": "2.8.5",
"cross-env": "7.0.3",
"express": "4.17.1",
"morgan": "1.10.0"
"joi": "^17.13.3",
"morgan": "1.10.0",
"nanoid": "^5.0.9"
},
"devDependencies": {
"eslint": "7.19.0",
Expand Down
77 changes: 59 additions & 18 deletions routes/api/contacts.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,66 @@
const express = require('express')
const express = require("express");
const Joi = require("joi");
const { listContacts, getContactById, addContact, removeContact } = require("../../models/contacts");

const router = express.Router()
const router = express.Router();

router.get('/', async (req, res, next) => {
res.json({ message: 'template message' })
})
// GET /api/contacts - pentru a obține lista de contacte
router.get("/", async (req, res) => {
try {
const contacts = await listContacts();
res.status(200).json(contacts);
} catch (error) {
res.status(500).json({ message: "Server error" });
}
});

router.get('/:contactId', async (req, res, next) => {
res.json({ message: 'template message' })
})
// GET /api/contacts/:id - pentru a obține un contact după ID
router.get("/:id", async (req, res) => {
const { id } = req.params;
try {
const contact = await getContactById(id);
if (!contact) {
return res.status(404).json({ message: "Contact not found" });
}
res.status(200).json(contact);
} catch (error) {
res.status(500).json({ message: "Server error" });
}
});

router.post('/', async (req, res, next) => {
res.json({ message: 'template message' })
})
// POST /api/contacts - pentru a adăuga un nou contact
router.post("/", async (req, res) => {
const { name, phone, email } = req.body;

router.delete('/:contactId', async (req, res, next) => {
res.json({ message: 'template message' })
})
const schema = Joi.object({
name: Joi.string().min(3).required(),
phone: Joi.string().required(),
email: Joi.string().email().required(),
});

router.put('/:contactId', async (req, res, next) => {
res.json({ message: 'template message' })
})
const { error } = schema.validate({ name, phone, email });
if (error) return res.status(400).send(error.details[0].message);

module.exports = router
try {
const newContact = await addContact({ name, phone, email });
res.status(201).json(newContact);
} catch (error) {
res.status(500).json({ message: "Server error" });
}
});

// DELETE /api/contacts/:id - pentru a șterge un contact
router.delete("/:id", async (req, res) => {
const { id } = req.params;
try {
const deletedContact = await removeContact(id);
if (!deletedContact) {
return res.status(404).json({ message: "Contact not found" });
}
res.status(200).json({ message: "Contact deleted successfully" });
} catch (error) {
res.status(500).json({ message: "Server error" });
}
});

module.exports = router;