-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontacts.js
67 lines (60 loc) · 1.76 KB
/
contacts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const fs = require('fs').promises;
const path = require('path');
// TODO: documentare fiecare funcție
//cale catre fisier contacts.json
const contactsPath = path.join(__dirname, 'db', 'contacts.json');
//lista toate contacte
async function listContacts() {
try {
const data = await fs.readFile(contactsPath, 'utf-8');
return JSON.parse(data);
} catch (error) {
console.error('Error reading contacts:', error);
return [];
}
}
//contact dupa id
async function getContactById(contactId) {
try {
const contacts = await listContacts();
return contacts.find(contact => contact.id === contactId) || null;
} catch (error) {
console.error('Error getting contact by ID:', error);
}
}
//sterge contact dupa id
async function removeContact(contactId) {
try {
const contacts = await listContacts();
const updatedContacts = contacts.filter(contact => contact.id !== contactId);
await fs.writeFile(contactsPath, JSON.stringify(updatedContacts, null, 2));
return true;
} catch (error) {
console.error('Error removing contact:', error);
return false;
}
}
//adugare contact nou
async function addContact(name, email, phone) {
try {
const contacts = await listContacts();
const newContact = {
id: String(Date.now()), // genereaza un ID nou
name,
email,
phone,
};
contacts.push(newContact);
await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2));
return newContact;
} catch (error) {
console.error('Error adding contact:', error);
}
}
//exporturi
module.exports = {
listContacts,
getContactById,
removeContact,
addContact,
};