-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontacts.js
More file actions
53 lines (46 loc) · 1.42 KB
/
contacts.js
File metadata and controls
53 lines (46 loc) · 1.42 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
import fs from "fs/promises";
import path from "path";
import { nanoid } from "nanoid";
const contactsPath = path.resolve("db/contacts.json");
export async function listContacts() {
try {
const data = await fs.readFile(contactsPath, "utf-8");
return JSON.parse(data);
} catch (error) {
throw new Error(error.message);
}
}
export async function getContactById(contactId) {
try {
const contacts = await listContacts();
const resultById = contacts.find((contact) => contact.id === contactId);
return resultById || null;
} catch (error) {
throw new Error(error.message);
}
}
export async function removeContact(contactId) {
try {
const contacts = await listContacts();
const contactToRemove = contacts.find(
(contact) => contact.id === contactId
);
if (!contactToRemove) return null;
const updatedContacts = contacts.filter(({ id }) => id !== contactId);
await fs.writeFile(contactsPath, JSON.stringify(updatedContacts, null, 2));
return contactToRemove;
} catch (error) {
throw new Error(error.message);
}
}
export async function addContact(name, email, phone) {
try {
const contacts = await listContacts();
const newContact = { id: nanoid(), name, email, phone };
contacts.push(newContact);
await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2));
return newContact;
} catch (error) {
throw new Error(error.message);
}
}