-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontacts.js
More file actions
56 lines (49 loc) · 1.31 KB
/
contacts.js
File metadata and controls
56 lines (49 loc) · 1.31 KB
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
const fs = require("fs").promises;
const path = require("path");
const contactsPath = path.resolve("./db/contacts.json");
const newId = Math.floor(Math.random() * 100);
async function listContacts() {
try {
const data = await fs.readFile(contactsPath);
const contacts = JSON.parse(data);
return contacts;
} catch (error) {
console.log(error);
}
}
async function getContactById(contactId) {
try {
const contacts = await listContacts();
const contactById = contacts.find((contact) => contact.id === contactId);
console.table(contactById);
} catch (error) {
console.log(error);
}
}
async function removeContact(contactId) {
const contacts = await listContacts();
const filteredContacts = contacts.filter(contact => contact.id !== contactId);
const newList = JSON.stringify(filteredContacts);
await fs.writeFile(contactsPath, `${newList}`);
}
async function addContact(name, email, phone) {
try {
const newContact = {
id: `${newId}`,
name,
email,
phone,
};
const contacts = await listContacts();
const newList = JSON.stringify([...contacts, newContact]);
await fs.writeFile(contactsPath, `${newList}`);
} catch (error) {
console.log(error);
}
}
module.exports = {
listContacts,
getContactById,
removeContact,
addContact,
};