diff --git a/app.js b/app.js index 40fd9bc167f..7e0cd143546 100644 --- a/app.js +++ b/app.js @@ -1,25 +1,25 @@ -const express = require('express') -const logger = require('morgan') -const cors = require('cors') +import express from "express"; +import logger from "morgan"; +import cors from "cors"; -const contactsRouter = require('./routes/api/contacts') +import { router as contactsRouter } from "./routes/api/contactsRouter.js"; -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('/api/contacts', contactsRouter) +app.use(logger(formatsLogger)); +app.use(cors()); +app.use(express.json()); +// http://localhost:3000/api/contacts +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 +export { app }; diff --git a/helpers/httpError.js b/helpers/httpError.js new file mode 100644 index 00000000000..d20f40ae3b6 --- /dev/null +++ b/helpers/httpError.js @@ -0,0 +1,15 @@ +const messages = { + 400: "Bad request", + 401: "Unauthorized", + 403: "Forbidden", + 404: "Not found", + 409: "Conflict", +}; + +const httpError = (status, message = messages[status]) => { + const error = new Error(message); + error.status = status; + return error; +}; + +export { httpError }; diff --git a/images/Delete_contact.png b/images/Delete_contact.png new file mode 100644 index 00000000000..673696883fa Binary files /dev/null and b/images/Delete_contact.png differ diff --git a/images/Get_allContacts.png b/images/Get_allContacts.png new file mode 100644 index 00000000000..c6040c19eab Binary files /dev/null and b/images/Get_allContacts.png differ diff --git a/images/Get_by_id.png b/images/Get_by_id.png new file mode 100644 index 00000000000..fec529fc235 Binary files /dev/null and b/images/Get_by_id.png differ diff --git a/images/Post_contact (2).png b/images/Post_contact (2).png new file mode 100644 index 00000000000..2d658dfa6de Binary files /dev/null and b/images/Post_contact (2).png differ diff --git a/images/Post_contact.png b/images/Post_contact.png new file mode 100644 index 00000000000..1792da85339 Binary files /dev/null and b/images/Post_contact.png differ diff --git a/images/Postman.png b/images/Postman.png new file mode 100644 index 00000000000..475148f4199 Binary files /dev/null and b/images/Postman.png differ diff --git a/images/Put_update.png b/images/Put_update.png new file mode 100644 index 00000000000..85b59dff695 Binary files /dev/null and b/images/Put_update.png differ diff --git a/models/contacts.js b/models/contacts.js index 409d11c7c09..df963de1b9a 100644 --- a/models/contacts.js +++ b/models/contacts.js @@ -1,19 +1,79 @@ -// const fs = require('fs/promises') +import fs from "fs/promises"; +// const fs from "fs/promises"; +import path from "path"; +import { nanoid } from "nanoid"; -const listContacts = async () => {} +const contactsPath = path.join("models", "contacts.json"); -const getContactById = async (contactId) => {} +const listContacts = async () => { + try { + const contacts = await fs.readFile(contactsPath); + return JSON.parse(contacts); + } catch (error) { + console.error("Error reading contacts:", error.message); + } +}; -const removeContact = async (contactId) => {} +const getContactById = async (contactId) => { + try { + const contacts = await listContacts(); + const result = contacts.find((contact) => contact.id === contactId); + return result || null; + } catch (error) { + console.error("Error reading contacts by id:", error.message); + } +}; -const addContact = async (body) => {} +const removeContact = async (contactId) => { + try { + const contacts = await listContacts(); + const index = contacts.findIndex((item) => item.id === contactId); + if (index === -1) { + return null; + } + const deletedContact = contacts.splice(index, 1); + await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2)); + return deletedContact; + } catch (error) { + console.error("Error removing contact:", error.message); + } +}; -const updateContact = async (contactId, body) => {} +const addContact = async ({ name, email, phone }) => { + try { + const contacts = await listContacts(); + const newContact = { + id: nanoid(), + name, + email, + phone, + }; + const allContacts = [...contacts, newContact]; + await fs.writeFile(contactsPath, JSON.stringify(allContacts, null, 2)); + return newContact; + } catch (error) { + console.error("Error adding new contact:", error.message); + } +}; -module.exports = { - listContacts, - getContactById, - removeContact, - addContact, - updateContact, -} +const updateContact = async (id, { name, email, phone }) => { + const contacts = await listContacts(); + const index = contacts.findIndex((item) => item.id === id); + + if (index === -1) { + return null; + } + + contacts[index] = { + id, + name, + email, + phone, + }; + + await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2)); + return contacts[index]; +}; + +// prettier-ignore +export { listContacts, getContactById, removeContact, addContact, updateContact }; diff --git a/models/contacts.json b/models/contacts.json index a21679132de..08f265cba3b 100644 --- a/models/contacts.json +++ b/models/contacts.json @@ -41,12 +41,6 @@ "email": "pharetra.ut@dictum.co.uk", "phone": "(715) 598-5792" }, - { - "id": "C9sjBfCo4UJCWjzBnOtxl", - "name": "Simon Morton", - "email": "dui.Fusce.diam@Donec.com", - "phone": "(233) 738-2360" - }, { "id": "e6ywwRe4jcqxXfCZOj_1e", "name": "Thomas Lucas", @@ -58,5 +52,17 @@ "name": "Alec Howard", "email": "Donec.elementum@scelerisquescelerisquedui.net", "phone": "(748) 206-2688" + }, + { + "id": "FolUehVRM8pfWysPJ6Ksx", + "name": "Manuel Saavedra Jr", + "email": "newojunior@gmail.com", + "phone": "(649) 5555" + }, + { + "id": "5xTD4iIVlbRp6bzQHncm8", + "name": "Simon Morton", + "email": "dui.Fusce.diam@Donec.com", + "phone": "(233) 738-2360" } -] +] \ No newline at end of file diff --git a/models/mockData.js b/models/mockData.js new file mode 100644 index 00000000000..e661ba781c6 --- /dev/null +++ b/models/mockData.js @@ -0,0 +1,6 @@ +export const mockData = [ + { id: 1, name: "Owen Saavedra", email: "newojunior@gmail.com" }, + { id: 2, name: "Newo Ardevaz", email: "manuelcsaavedrajr@gmail.com" }, + { id: 3, name: "Melanie Saavedra", email: "malaniesaavedra@gmail.com" }, + { id: 4, name: "Melanie Cetron", email: "malaniecetron@gmail.com" }, +]; diff --git a/package-lock.json b/package-lock.json index e6d047044e5..6700e88eb85 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.7" }, "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.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.0.7.tgz", + "integrity": "sha512-oLxFY2gd2IqnjcYyOXD8XGCftpGtZP2AbHbOkthDkvRywH5ayNtPVy9YlOPcHckXzbLTCHpkb7FB+yuxKV13pQ==", + "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.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.0.7.tgz", + "integrity": "sha512-oLxFY2gd2IqnjcYyOXD8XGCftpGtZP2AbHbOkthDkvRywH5ayNtPVy9YlOPcHckXzbLTCHpkb7FB+yuxKV13pQ==" + }, "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..736d6c50732 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,7 @@ "name": "template", "version": "0.0.0", "private": true, + "type": "module", "scripts": { "start": "cross-env NODE_ENV=production node ./server.js", "start:dev": "cross-env NODE_ENV=development nodemon ./server.js", @@ -12,7 +13,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.7" }, "devDependencies": { "eslint": "7.19.0", diff --git a/routes/api/contacts.js b/routes/api/contacts.js deleted file mode 100644 index a60ebd69231..00000000000 --- a/routes/api/contacts.js +++ /dev/null @@ -1,25 +0,0 @@ -const express = require('express') - -const router = express.Router() - -router.get('/', async (req, res, next) => { - res.json({ message: 'template message' }) -}) - -router.get('/:contactId', async (req, res, next) => { - res.json({ message: 'template message' }) -}) - -router.post('/', async (req, res, next) => { - res.json({ message: 'template message' }) -}) - -router.delete('/:contactId', async (req, res, next) => { - res.json({ message: 'template message' }) -}) - -router.put('/:contactId', async (req, res, next) => { - res.json({ message: 'template message' }) -}) - -module.exports = router diff --git a/routes/api/contactsRouter.js b/routes/api/contactsRouter.js new file mode 100644 index 00000000000..e6b36abaa17 --- /dev/null +++ b/routes/api/contactsRouter.js @@ -0,0 +1,119 @@ +import express from "express"; +// import { mockData } from "../../models/mockData.js"; +// prettier-ignore +import { listContacts, getContactById, removeContact, addContact, updateContact } from "../../models/contacts.js"; +import { contactValidation } from "../../validations/validation.js"; +import { httpError } from "../../helpers/httpError.js"; + +const router = express.Router(); + +// Read +// http://localhost:3000/api/contacts/ +router.get("/", async (_req, res, next) => { + // res.json({ message: "template message" }); + try { + // Logic Here + const result = await listContacts(); + res.json(result); + // res.json(mockData); + } catch (error) { + next(error); + } +}); +// Read +// http://localhost:3000/api/contacts/1 +router.get("/:contactId", async (req, res, next) => { + // res.json({ message: "template message" }); + try { + // Logic here + const { contactId } = req.params; + const result = await getContactById(contactId); + // const contact = mockData.find( + // (contact) => contact.id === parseInt(contactId) + // ); + // if (!contact) { + // const err = new Error("Contact not found"); + // err.status = 404; + // return next(err); + // } + if (!result) { + throw httpError(404); + } + + res.json(result); + } catch (error) { + next(error); + } +}); +// create +// http://localhost:3000/api/contacts/ +router.post("/", async (req, res, next) => { + // res.json({ message: "template message" }); + try { + // Preventing lack of necessary data + const { error } = contactValidation.validate(req.body); + if (error) { + throw httpError(400, "missing required name field"); + } + // const { name, email } = req.body; + // const newContact = { id: mockData.length + 1, name, email }; + // mockData.push(newContact); + const result = await addContact(req.body); + res.status(201).json(result); + } catch (error) { + next(error); + } +}); +// Delete +// http://localhost:3000/api/contacts/2 +router.delete("/:contactId", async (req, res, next) => { + // res.json({ message: "template message" }); + try { + // Logic here + const { contactId } = req.params; + const result = await removeContact(contactId); + // mockData.filter((contact) => contact.id !== parseInt(contactId)); + if (!result) { + throw httpError(404); + } + res.json({ message: "Contact deleted" }); + } catch (error) { + next(error); + } +}); +// Update +// http://localhost:3000/api/contacts/2 +router.put("/:contactId", async (req, res, next) => { + // res.json({ message: "template message" }); + try { + // preventing lack of necessary data + const { error } = contactValidation.validate(req.body); + if (error) { + throw httpError(400, "missing field"); + } + + const { contactId } = req.params; + // const { name, email } = req.body; + const result = await updateContact(contactId, req.body); + + if (!result) { + throw httpError(404); + } + // const index = mockData.findIndex( + // (contact) => contact.id === parseInt(contactId) + // ); + // if (index === -1) { + // const err = new Error("Contact not found"); + // err.status = 404; + // return next(err); + // } + // mockData[index] = { ...mockData[index], name, email }; + // res.json(mockData[index]); + res.json(result); + } catch (error) { + next(error); + } +}); + +export { router }; +// module.exports = router; diff --git a/server.js b/server.js index fc4e4c6bb3a..6986ff6bd7b 100644 --- a/server.js +++ b/server.js @@ -1,4 +1,5 @@ -const app = require("./app"); +import { app } from "./app.js"; +// const app = require("./app"); converted ESM app.listen(3000, () => { console.log("Server is running. Use our API on port: 3000"); diff --git a/validations/validation.js b/validations/validation.js new file mode 100644 index 00000000000..284b6e89c09 --- /dev/null +++ b/validations/validation.js @@ -0,0 +1,11 @@ +import Joi from "joi"; + +// Define validation for adding a contact +const contactValidation = Joi.object({ + name: Joi.string().required(), + email: Joi.string().required(), + phone: Joi.string().required(), + favorite: Joi.boolean(), +}); + +export { contactValidation };