Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tema hw02: Adăugat REST API pentru colecția de contacte #5509

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
48 changes: 41 additions & 7 deletions models/contacts.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,53 @@
// const fs = require('fs/promises')
const fs = require("fs/promises");
const path = require("path");
const { v4: uuidv4 } = require("uuid");
const contactsPath = path.join(__dirname, "contacts.json");

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

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

const removeContact = async (contactId) => {}
const removeContact = async (contactId) => {
const contacts = await listContacts();
const updatedContacts = contacts.filter(
(contact) => contact.id !== contactId
);
if (contacts.length === updatedContacts.length) {
return null;
}
await fs.writeFile(contactsPath, JSON.stringify(updatedContacts));
return { message: "Contact deleted" };
};

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

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

module.exports = {
listContacts,
getContactById,
removeContact,
addContact,
updateContact,
}
};
2 changes: 1 addition & 1 deletion models/contacts.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[
{
"id": "AeHIrLTr6JkxGE6SN-0Rw",
"name": "Allen Raymond",
"name": "Andra",
"email": "nulla.ante@vestibul.co.uk",
"phone": "(992) 914-3792"
},
Expand Down
107 changes: 106 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",
"uuid": "^11.0.3"
},
"devDependencies": {
"eslint": "7.19.0",
Expand Down
98 changes: 80 additions & 18 deletions routes/api/contacts.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,87 @@
const express = require('express')
const express = require("express");
const Joi = require("joi");
const {
listContacts,
getContactById,
removeContact,
addContact,
updateContact,
} = require("../../models/contacts");

const router = express.Router()
// Joi schema for validation
const contactSchema = Joi.object({
name: Joi.string().required(),
email: Joi.string().email().required(),
phone: Joi.string().required(),
});

router.get('/', async (req, res, next) => {
res.json({ message: 'template message' })
})
const router = express.Router();

router.get('/:contactId', async (req, res, next) => {
res.json({ message: 'template message' })
})
// GET /api/contacts
router.get("/", async (req, res, next) => {
try {
const contacts = await listContacts();
res.status(200).json(contacts);
} catch (error) {
next(error);
}
});

router.post('/', async (req, res, next) => {
res.json({ message: 'template message' })
})
// GET /api/contacts/:contactId
router.get("/:contactId", async (req, res, next) => {
try {
const contact = await getContactById(req.params.contactId);
if (!contact) {
return res.status(404).json({ message: "Not found" });
}
res.status(200).json(contact);
} catch (error) {
next(error);
}
});

router.delete('/:contactId', async (req, res, next) => {
res.json({ message: 'template message' })
})
// POST /api/contacts
router.post("/", async (req, res, next) => {
try {
const { error } = contactSchema.validate(req.body);
if (error) {
return res.status(400).json({ message: "missing required fields" });
}
const newContact = await addContact(req.body);
res.status(201).json(newContact);
} catch (error) {
next(error);
}
});

router.put('/:contactId', async (req, res, next) => {
res.json({ message: 'template message' })
})
// DELETE /api/contacts/:contactId
router.delete("/:contactId", async (req, res, next) => {
try {
const result = await removeContact(req.params.contactId);
if (!result) {
return res.status(404).json({ message: "Not found" });
}
res.status(200).json(result);
} catch (error) {
next(error);
}
});

module.exports = router
// PUT /api/contacts/:contactId
router.put("/:contactId", async (req, res, next) => {
try {
if (Object.keys(req.body).length === 0) {
return res.status(400).json({ message: "missing fields" });
}

const updatedContact = await updateContact(req.params.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;