-
Notifications
You must be signed in to change notification settings - Fork 0
/
contacts.js
60 lines (51 loc) · 1.24 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
const fs = require('fs').promises;
const path = require('node:path');
const { nanoid } = require('nanoid');
console.log(__dirname);
const contactsPath = path.join(
__dirname,
'db/contacts.json'
);
console.log(contactsPath);
const updateContacts = async contacts =>
await fs.writeFile(
contactsPath,
JSON.stringify(contacts, null, 2)
);
const listContacts = async () => {
const result = await fs.readFile(contactsPath);
return JSON.parse(result);
};
const getContactById = async id => {
const contacts = await listContacts();
const result = contacts.find(item => item.id === id);
return result || null;
};
const addContact = async ({ name, email, phone }) => {
const contacts = await listContacts();
const newContact = {
id: nanoid(),
name,
email,
phone,
};
contacts.push(newContact);
await updateContacts(contacts);
return newContact;
};
const removeContact = async id => {
const contacts = await listContacts();
const index = contacts.findIndex(item => item.id === id);
if (index === -1) {
return null;
}
const [result] = contacts.splice(index, 1);
await updateContacts(contacts);
return result;
};
module.exports = {
listContacts,
getContactById,
addContact,
removeContact,
};