diff --git a/app.js b/app.js index 40fd9bc167f..1df09b71cd0 100644 --- a/app.js +++ b/app.js @@ -1,25 +1,25 @@ -const express = require('express') -const logger = require('morgan') -const cors = require('cors') +const express = require("express"); +const logger = require("morgan"); +const cors = require("cors"); -const contactsRouter = require('./routes/api/contacts') +const contactsRouter = require("./routes/api/contacts"); -const app = express() +const app = express(); -const formatsLogger = app.get('env') === 'development' ? 'dev' : 'short' +const formatsLogger = app.get("env") === "development" ? "dev" : "short"; -app.use(logger(formatsLogger)) -app.use(cors()) -app.use(express.json()) +app.use(logger(formatsLogger)); +app.use(cors()); +app.use(express.json()); -app.use('/api/contacts', contactsRouter) +app.use("/api/contacts", contactsRouter); app.use((req, res) => { - res.status(404).json({ message: 'Not found' }) -}) + res.status(404).json({ message: "Not found" }); +}); app.use((err, req, res, next) => { - res.status(500).json({ message: err.message }) -}) + 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..86a1eb712bd 100644 --- a/models/contacts.js +++ b/models/contacts.js @@ -1,14 +1,67 @@ -// const fs = require('fs/promises') +const { read } = require("fs"); +const fs = require("fs/promises"); +const path = require("path"); +const { v4: uuidv4 } = require("uuid"); -const listContacts = async () => {} +const contactsPath = path.join(__dirname, "contacts.json"); -const getContactById = async (contactId) => {} +const readContactsFile = async () => { + try { + const data = await fs.readFile(contactsPath, "utf-8"); + return JSON.parse(data); + } catch (error) { + console.error("Error reading contacts file:", error.message); + return []; + } +}; -const removeContact = async (contactId) => {} +const writeContactsFile = async (contacts) => { + try { + await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2)); + } catch (error) { + console.error("Error writing contacts file:", error.message); + } +}; -const addContact = async (body) => {} +const listContacts = async () => { + return await readContactsFile(); +}; -const updateContact = async (contactId, body) => {} +const getContactById = async (contactId) => { + const contacts = await readContactsFile(); + return contacts.find((contact) => contact.id === contactId) || null; +}; + +const removeContact = async (contactId) => { + const contacts = await readContactsFile(); + const index = contacts.findIndex((contact) => contact.id === contactId); + + if (index === -1) return null; + + const [removedContact] = contacts.splice(index, 1); + await writeContactsFile(contacts); + return removedContact; +}; + +const addContact = async (body) => { + const contacts = await readContactsFile(); + const newContact = { id: uuidv4(), ...body }; + + contacts.push(newContact); + await writeContactsFile(contacts); + return newContact; +}; + +const updateContact = async (contactId, body) => { + const contacts = await readContactsFile(); + const index = contacts.findIndex((contact) => contact.id === contactId); + + if (index === -1) return null; + + contacts[index] = { ...contacts[index], ...body }; + await writeContactsFile(contacts); + return contacts[index]; +}; module.exports = { listContacts, @@ -16,4 +69,4 @@ module.exports = { removeContact, addContact, updateContact, -} +}; diff --git a/models/contacts.json b/models/contacts.json index a21679132de..913a0e4da33 100644 --- a/models/contacts.json +++ b/models/contacts.json @@ -1,9 +1,9 @@ [ { "id": "AeHIrLTr6JkxGE6SN-0Rw", - "name": "Allen Raymond", - "email": "nulla.ante@vestibul.co.uk", - "phone": "(992) 914-3792" + "name": "Sebastian", + "email": "Sebastian@example.com", + "phone": "123456789" }, { "id": "qdggE76Jtbfd9eWJHrssH", @@ -58,5 +58,11 @@ "name": "Alec Howard", "email": "Donec.elementum@scelerisquescelerisquedui.net", "phone": "(748) 206-2688" + }, + { + "id": "c967f137-6519-4c36-a0a2-1110e98fce27", + "name": "Aaaaa Test", + "email": "at@example.com", + "phone": "11111111" } -] +] \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index e6d047044e5..09d7e9486d8 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", + "uuid": "^11.0.2" }, "devDependencies": { "eslint": "7.19.0", @@ -141,6 +143,42 @@ "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==", + "license": "BSD-3-Clause" + }, + "node_modules/@hapi/topo": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@hapi/topo/-/topo-5.1.0.tgz", + "integrity": "sha512-foQZKJig7Ob0BMAYBfcJk8d77QtOe7Wo4ox7ff1lQYoNNAb6jwcY1ncdoy2e9wQZzvNy7ODZCYJkK8kzmcAnAg==", + "license": "BSD-3-Clause", + "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==", + "license": "BSD-3-Clause", + "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==", + "license": "BSD-3-Clause" + }, + "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==", + "license": "BSD-3-Clause" + }, "node_modules/@sindresorhus/is": { "version": "0.14.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", @@ -2166,6 +2204,19 @@ "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==", + "license": "BSD-3-Clause", + "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", @@ -3544,6 +3595,19 @@ "node": ">= 0.4.0" } }, + "node_modules/uuid": { + "version": "11.0.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.0.2.tgz", + "integrity": "sha512-14FfcOJmqdjbBPdDjFQyk/SdT4NySW4eM0zcG+HqbHP5jzuH56xO3J1DGhgs/cEMCfwYi3HQI1gnTO62iaG+tQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, "node_modules/v8-compile-cache": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", @@ -3757,6 +3821,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 +5364,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", @@ -6326,6 +6433,11 @@ "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=" }, + "uuid": { + "version": "11.0.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.0.2.tgz", + "integrity": "sha512-14FfcOJmqdjbBPdDjFQyk/SdT4NySW4eM0zcG+HqbHP5jzuH56xO3J1DGhgs/cEMCfwYi3HQI1gnTO62iaG+tQ==" + }, "v8-compile-cache": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", diff --git a/package.json b/package.json index 5045e827160..f6b7a89a531 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", + "uuid": "^11.0.2" }, "devDependencies": { "eslint": "7.19.0", diff --git a/routes/api/contacts.js b/routes/api/contacts.js index a60ebd69231..bf03c135b7a 100644 --- a/routes/api/contacts.js +++ b/routes/api/contacts.js @@ -1,25 +1,83 @@ -const express = require('express') +const express = require("express"); +const router = express.Router(); +const contacts = require("../../models/contacts"); +const Joi = require("joi"); -const router = express.Router() +const contactSchema = Joi.object({ + name: Joi.string().required(), + email: Joi.string().email().required(), + phone: Joi.string().pattern(/^\d+$/).required(), +}); -router.get('/', async (req, res, next) => { - res.json({ message: 'template message' }) -}) +router.get("/", async (req, res, next) => { + try { + const allContacts = await contacts.listContacts(); + res.status(200).json(allContacts); + } catch (error) { + next(error); + } +}); -router.get('/:contactId', async (req, res, next) => { - res.json({ message: 'template message' }) -}) +router.get("/:contactId", async (req, res, next) => { + try { + const { contactId } = req.params; + const contact = await contacts.getContactById(contactId); + if (!contact) { + return res.status(404).json({ message: "Not found" }); + } + res.status(200).json(contact); + } catch (error) { + next(error); + } +}); -router.post('/', async (req, res, next) => { - res.json({ message: 'template message' }) -}) +router.post("/", async (req, res, next) => { + try { + const { error } = contactSchema.validate(req.body); + if (error) { + return res + .status(400) + .json({ message: `Validation error: ${error.details[0].message}` }); + } -router.delete('/:contactId', async (req, res, next) => { - res.json({ message: 'template message' }) -}) + const newContact = await contacts.addContact(req.body); + res.status(201).json(newContact); + } catch (error) { + next(error); + } +}); -router.put('/:contactId', async (req, res, next) => { - res.json({ message: 'template message' }) -}) +router.delete("/:contactId", async (req, res, next) => { + try { + const { contactId } = req.params; + const result = await contacts.removeContact(contactId); + if (!result) { + return res.status(404).json({ message: "Not found" }); + } + res.status(200).json({ message: "contact deleted" }); + } catch (error) { + next(error); + } +}); -module.exports = router +router.put("/:contactId", async (req, res, next) => { + try { + const { error } = contactSchema.validate(req.body); + if (error) { + return res + .status(400) + .json({ message: `Validation error: ${error.details[0].message}` }); + } + + const { contactId } = req.params; + const updatedContact = await contacts.updateContact(contactId, req.body); + if (!updatedContact) { + return res.status(404).json({ message: "Not found" }); + } + res.status(200).json(updatedContact); + } catch (error) { + next(error); + } +}); + +module.exports = router;