-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontacts.js
65 lines (52 loc) · 1.75 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
import fs from "fs/promises";
import path from "path";
import { nanoid } from "nanoid";
// CommonJS: -> path.join(__dirname, 'contacts.json')
const contactsPath = path.resolve("db", "contacts.json");
console.log(contactsPath);
export const listContacts = async () => {
try {
const contactListBuffer = await fs.readFile(contactsPath);
const contactList = JSON.parse(contactListBuffer.toString());
if (!contactList.length) {
return "Contact list is empty";
}
return contactList;
} catch ({ message }) {
return message;
}
}
export const getContactById = async (contactId) => {
try {
const contactList = await listContacts();
const targetContact = contactList.find(({ id }) => id === contactId);
return targetContact || null;
} catch ({ message }) {
return message;
}
}
export const addContact = async (name, email, phone) => {
try {
const contactList = await listContacts();
const newContact = { id: nanoid(), name, email, phone };
contactList.push(newContact);
await fs.writeFile(contactsPath, JSON.stringify(contactList, null, 2));
return newContact;
} catch ({ message }) {
return message;
}
}
export const removeContact = async (contactId) => {
try {
const contactList = await listContacts();
const contactIndex = contactList.findIndex(({ id }) => id === contactId);
if (contactIndex === -1) {
return null;
}
const [removedContact] = contactList.splice(contactIndex, 1);
await fs.writeFile(contactsPath, JSON.stringify(contactList, null, 2));
return removedContact;
} catch ({ message }) {
return message;
}
}