diff --git a/app.js b/app.js index 40fd9bc167f..b13d0931afe 100644 --- a/app.js +++ b/app.js @@ -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; diff --git a/models/contacts.js b/models/contacts.js index 409d11c7c09..ccaa2e96659 100644 --- a/models/contacts.js +++ b/models/contacts.js @@ -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 } diff --git a/models/contacts.json b/models/contacts.json index a21679132de..7e4ed721b24 100644 --- a/models/contacts.json +++ b/models/contacts.json @@ -59,4 +59,4 @@ "email": "Donec.elementum@scelerisquescelerisquedui.net", "phone": "(748) 206-2688" } -] +] \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index e6d047044e5..77850576336 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,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", @@ -141,6 +143,37 @@ "node": "^10.12.0 || >=12.0.0" } }, + "node_modules/@hapi/hoek": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", + "integrity": "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ==" + }, + "node_modules/@hapi/topo": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@hapi/topo/-/topo-5.1.0.tgz", + "integrity": "sha512-foQZKJig7Ob0BMAYBfcJk8d77QtOe7Wo4ox7ff1lQYoNNAb6jwcY1ncdoy2e9wQZzvNy7ODZCYJkK8kzmcAnAg==", + "dependencies": { + "@hapi/hoek": "^9.0.0" + } + }, + "node_modules/@sideway/address": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@sideway/address/-/address-4.1.5.tgz", + "integrity": "sha512-IqO/DUQHUkPeixNQ8n0JA6102hT9CmaljNTPmQ1u8MEhBo/R4Q8eKLN/vGZxuebwOroDB4cbpjheD4+/sKFK4Q==", + "dependencies": { + "@hapi/hoek": "^9.0.0" + } + }, + "node_modules/@sideway/formula": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@sideway/formula/-/formula-3.0.1.tgz", + "integrity": "sha512-/poHZJJVjx3L+zVD6g9KgHfYnb443oi7wLu/XKojDviHy6HOEOA6z1Trk5aR1dGcmPenJEgb2sK2I80LeS3MIg==" + }, + "node_modules/@sideway/pinpoint": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@sideway/pinpoint/-/pinpoint-2.0.0.tgz", + "integrity": "sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ==" + }, "node_modules/@sindresorhus/is": { "version": "0.14.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", @@ -2166,6 +2199,18 @@ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" }, + "node_modules/joi": { + "version": "17.13.3", + "resolved": "https://registry.npmjs.org/joi/-/joi-17.13.3.tgz", + "integrity": "sha512-otDA4ldcIx+ZXsKHWmp0YizCweVRZG96J10b0FevjfuncLO1oX59THoAmHkNubYJ+9gWsYsp5k8v4ib6oDv1fA==", + "dependencies": { + "@hapi/hoek": "^9.3.0", + "@hapi/topo": "^5.1.0", + "@sideway/address": "^4.1.5", + "@sideway/formula": "^3.0.1", + "@sideway/pinpoint": "^2.0.0" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -2439,6 +2484,23 @@ "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", "dev": true }, + "node_modules/nanoid": { + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.0.9.tgz", + "integrity": "sha512-Aooyr6MXU6HpvvWXKoVoXwKMs/KyVakWwg7xQfv5/S/RIgJMy0Ifa45H9qqYy7pTCszrHzP21Uk4PZq2HpEM8Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.js" + }, + "engines": { + "node": "^18 || >=20" + } + }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", @@ -3757,6 +3819,37 @@ "strip-json-comments": "^3.1.1" } }, + "@hapi/hoek": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", + "integrity": "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ==" + }, + "@hapi/topo": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@hapi/topo/-/topo-5.1.0.tgz", + "integrity": "sha512-foQZKJig7Ob0BMAYBfcJk8d77QtOe7Wo4ox7ff1lQYoNNAb6jwcY1ncdoy2e9wQZzvNy7ODZCYJkK8kzmcAnAg==", + "requires": { + "@hapi/hoek": "^9.0.0" + } + }, + "@sideway/address": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@sideway/address/-/address-4.1.5.tgz", + "integrity": "sha512-IqO/DUQHUkPeixNQ8n0JA6102hT9CmaljNTPmQ1u8MEhBo/R4Q8eKLN/vGZxuebwOroDB4cbpjheD4+/sKFK4Q==", + "requires": { + "@hapi/hoek": "^9.0.0" + } + }, + "@sideway/formula": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@sideway/formula/-/formula-3.0.1.tgz", + "integrity": "sha512-/poHZJJVjx3L+zVD6g9KgHfYnb443oi7wLu/XKojDviHy6HOEOA6z1Trk5aR1dGcmPenJEgb2sK2I80LeS3MIg==" + }, + "@sideway/pinpoint": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@sideway/pinpoint/-/pinpoint-2.0.0.tgz", + "integrity": "sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ==" + }, "@sindresorhus/is": { "version": "0.14.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", @@ -5269,6 +5362,18 @@ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" }, + "joi": { + "version": "17.13.3", + "resolved": "https://registry.npmjs.org/joi/-/joi-17.13.3.tgz", + "integrity": "sha512-otDA4ldcIx+ZXsKHWmp0YizCweVRZG96J10b0FevjfuncLO1oX59THoAmHkNubYJ+9gWsYsp5k8v4ib6oDv1fA==", + "requires": { + "@hapi/hoek": "^9.3.0", + "@hapi/topo": "^5.1.0", + "@sideway/address": "^4.1.5", + "@sideway/formula": "^3.0.1", + "@sideway/pinpoint": "^2.0.0" + } + }, "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -5486,6 +5591,11 @@ "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", "dev": true }, + "nanoid": { + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.0.9.tgz", + "integrity": "sha512-Aooyr6MXU6HpvvWXKoVoXwKMs/KyVakWwg7xQfv5/S/RIgJMy0Ifa45H9qqYy7pTCszrHzP21Uk4PZq2HpEM8Q==" + }, "natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", diff --git a/package.json b/package.json index 5045e827160..13a3e4c4fcb 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/routes/api/contacts.js b/routes/api/contacts.js index a60ebd69231..0e6ebf74ec3 100644 --- a/routes/api/contacts.js +++ b/routes/api/contacts.js @@ -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;