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

Hw02 express #5493

Open
wants to merge 6 commits 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
94 changes: 87 additions & 7 deletions models/contacts.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,99 @@
// const fs = require('fs/promises')
const fs = require('fs').promises;
const { v4: uuidv4 } = require('uuid');
const Joi = require('joi');

const listContacts = async () => {}
const contactsPath = './models/contacts.json';

const getContactById = async (contactId) => {}
const validationSchema = Joi.object({
name: Joi.string().alphanum().min(3).max(20).required(),
email: Joi.string().email({ minDomainSegments: 2, tlds: { allow: ['com', 'pl'] } }).required(),
phone: Joi.string().required(),
});

const removeContact = async (contactId) => {}
async function listContacts() {
try {
const data = await fs.readFile(contactsPath, 'utf8');
return JSON.parse(data);
} catch (err) {
throw new Error('Error reading contacts:', err.message);
}
}

async function getContactById(contactId) {
try {
const contacts = await listContacts();
return contacts.find(contact => contact.id === contactId) || null;
} catch (err) {
throw new Error(`Error finding contact with ID ${contactId}:`, err.message);
}
}

async function removeContact(contactId) {
try {
const contacts = await listContacts();
const updatedContacts = contacts.filter(contact => contact.id !== contactId);

const addContact = async (body) => {}
if (contacts.length === updatedContacts.length) {
console.log(`Contact with ID ${contactId} not found.`);
return;
}

const updateContact = async (contactId, body) => {}
await fs.writeFile(contactsPath, JSON.stringify(updatedContacts, null, 2));
console.log(`Contact with ID ${contactId} has been removed.`);
} catch (err) {
throw new Error(`Error removing contact with ID ${contactId}:`, err.message);
}
}

async function addContact(name, email, phone) {
try {
const { error } = validationSchema.validate({ name, email, phone });
if (error) {
throw new Error(`Validation error: ${error.details[0].message}`);
}

const contacts = await listContacts();
const newContact = {
id: uuidv4(),
name,
email,
phone,
};

contacts.push(newContact);
await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2));
console.log('Contact has been added:', newContact);
return newContact;
} catch (err) {
throw new Error('Error adding contact:', err.message);
}
}

async function updateContact(contactId, body) {
try {
const { error } = validationSchema.validate(body);
if (error) {
throw new Error(`Validation error: ${error.details[0].message}`);
}

const contacts = await listContacts();
const contactIndex = contacts.findIndex(contact => contact.id === contactId);
if (contactIndex === -1) return null;

const updatedContact = { ...contacts[contactIndex], ...body };
contacts[contactIndex] = updatedContact;

await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2));
return updatedContact;
} catch (err) {
throw new Error(`Error updating contact with ID ${contactId}:`, err.message);
}
}

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
Expand Up @@ -59,4 +59,4 @@
"email": "[email protected]",
"phone": "(748) 206-2688"
}
]
]
125 changes: 121 additions & 4 deletions package-lock.json

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

17 changes: 12 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
"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",
"uuid": "^11.0.2"
},
"devDependencies": {
"eslint": "7.19.0",
Expand All @@ -21,6 +23,11 @@
"eslint-plugin-import": "2.25.3",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "5.2.0",
"nodemon": "2.0.15"
}
"nodemon": "^2.0.15"
},
"description": "Wykonaj forka tego repozytorium, aby wykonywać zadania domowe (2-6). Fork utworzy repozytorium na Twoim koncie na http://github.com",
"main": ".eslintrc.js",
"keywords": [],
"author": "",
"license": "ISC"
}
27 changes: 0 additions & 27 deletions readme.es.md

This file was deleted.

Loading