Skip to content
Open

Hm02 #77

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
44 changes: 44 additions & 0 deletions controllers/contactsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const contacts = require("../models/contacts");

async function getAll(req, res) {
const data = await contacts.listContacts();
res.status(200).json(data);
}

async function getById(req, res) {
const contact = await contacts.getById(req.params.id);
if (!contact) return res.status(404).json({ message: "Not found" });
res.status(200).json(contact);
}

async function create(req, res) {
const { name, email, phone } = req.body;
if (!name || !email || !phone) {
return res.status(400).json({ message: "missing required name field" });
}
const newContact = await contacts.addContact(req.body);
res.status(201).json(newContact);
}

async function remove(req, res) {
const result = await contacts.removeContact(req.params.id);
if (!result) return res.status(404).json({ message: "Not found" });
res.status(200).json({ message: "contact deleted" });
}

async function update(req, res) {
if (!req.body || Object.keys(req.body).length === 0) {
return res.status(400).json({ message: "missing fields" });
}
const updated = await contacts.updateContact(req.params.id, req.body);
if (!updated) return res.status(404).json({ message: "Not found" });
res.status(200).json(updated);
}

module.exports = {
getAll,
getById,
create,
remove,
update,
};
File renamed without changes.
48 changes: 39 additions & 9 deletions models/contacts.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,49 @@
// const fs = require('fs/promises')
const fs = require("fs/promises");
const path = require("path");
const { v4: uuidv4 } = require("uuid");

const listContacts = async () => {}
const contactsPath = path.join(__dirname, "../db/contacts.json");

const getContactById = async (contactId) => {}
async function listContacts() {
const data = await fs.readFile(contactsPath);
return JSON.parse(data);
}

const removeContact = async (contactId) => {}
async function getById(id) {
const contacts = await listContacts();
return contacts.find((contact) => contact.id === id) || null;
}

const addContact = async (body) => {}
async function addContact({ name, email, phone }) {
const contacts = await listContacts();
const newContact = { id: uuidv4(), name, email, phone };
contacts.push(newContact);
await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2));
return newContact;
}

const updateContact = async (contactId, body) => {}
async function removeContact(id) {
const contacts = await listContacts();
const index = contacts.findIndex((c) => c.id === id);
if (index === -1) return null;
const deleted = contacts.splice(index, 1);
await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2));
return deleted[0];
}

async function updateContact(id, body) {
const contacts = await listContacts();
const index = contacts.findIndex((c) => c.id === id);
if (index === -1) return null;
contacts[index] = { ...contacts[index], ...body };
await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2));
return contacts[index];
}

module.exports = {
listContacts,
getContactById,
removeContact,
getById,
addContact,
removeContact,
updateContact,
}
};
102 changes: 99 additions & 3 deletions package-lock.json

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

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
"lint:fix": "eslint --fix **/*.js"
},
"dependencies": {
"cors": "2.8.5",
"cors": "^2.8.5",
"cross-env": "7.0.3",
"express": "4.17.1",
"morgan": "1.10.0"
"express": "^4.17.1",
"joi": "^17.13.3",
"morgan": "^1.10.0"
},
"devDependencies": {
"eslint": "7.19.0",
Expand Down
33 changes: 24 additions & 9 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
## GoIT Node.js Course Template Homework

Please fork this repository to complete your homework assignments (2-6).
Forking will create a repository on your http://github.com account.
Realizează un fork al acestui repozitoriu pentru a îndeplini temele de acasă (2-6). Fork-ul va crea un repozitoriu pe contul tău de pe http://github.com

## Expalanation Recording to hanle homeworks in the Node.js Block
[Watch the video](https://www.loom.com/share/007c97d271604e02ae61adbb5b69edd3)
Adaugă mentorul la colaborare.

### Commands:
Pentru fiecare temă, creează un branch separat.

- `npm start` — starts the server in production mode.
- `npm run start:dev` — starts the server in development mode.
- `npm run lint` — runs eslint to check the code. Make sure to execute this before each PR and fix all linting errors.
- `npm lint:fix` — same as the previous command but fixes simple linting errors automatically.
- hw02
- hw03
- hw04
- hw05
- hw06

Fiecare branch nou pentru fiecare temă trebuie să fie derivat din branch-ul principal (master).

După ce ai terminat lucrul la tema de acasă în branch-ul tău, trebuie să creezi un pull request (PR). Apoi, adaugă mentorul pentru revizuirea codului. Abia după ce mentorul aprobă PR-ul, poți face "merge" a branch-ului cu tema de acasă în branch-ul master.

Citește cu atenție comentariile mentorului. Corectează observațiile și fă un "commit" în branch-ul cu tema de acasă. Modificările se vor reflecta automat în PR după ce trimiți "commit"-ul cu corecțiile pe GitHub. După corectare, adaugă din nou mentorul pentru revizuirea codului.

- La predarea temei de acasă, este furnizat un link către PR.
- Codul JavaScript este curat și ușor de înțeles, iar pentru formatare se folosește Prettier.

### Comenzi:

- `npm start` — pornește serverul în modul production.
- `npm run start:dev` — pornește serverul în modul dezvoltare (development).
- `npm run lint` — rulează verificarea codului cu ESLint, este necesar să se ruleze înaintea fiecărui PR și să se corecteze toate erorile linterului.
- `npm lint:fix` — aceeași verificare a linterului, dar cu corecții automate pentru erorile simple.
41 changes: 19 additions & 22 deletions routes/api/contacts.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
const express = require('express')
const express = require("express");
const router = express.Router();
const controller = require("../controllers/contactsController");
const { addSchema, updateSchema } = require("../validators/contactValidator");

const router = express.Router()
function validate(schema) {
return (req, res, next) => {
const { error } = schema.validate(req.body);
if (error) {
return res.status(400).json({ message: error.message });
}
next();
};
}

router.get('/', async (req, res, next) => {
res.json({ message: 'template message' })
})
router.get("/", controller.getAll);
router.get("/:id", controller.getById);
router.post("/", validate(addSchema), controller.create);
router.delete("/:id", controller.remove);
router.put("/:id", validate(updateSchema), controller.update);

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
module.exports = router;
15 changes: 15 additions & 0 deletions validators/contactsValidators.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const Joi = require("joi");

const addSchema = Joi.object({
name: Joi.string().required(),
email: Joi.string().email().required(),
phone: Joi.string().required(),
});

const updateSchema = Joi.object({
name: Joi.string(),
email: Joi.string().email(),
phone: Joi.string(),
}).min(1);

module.exports = { addSchema, updateSchema };