Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .eslintrc.js → .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,6 @@ module.exports = {
},
rules: {},
}



10 changes: 5 additions & 5 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const express = require('express')
const logger = require('morgan')
const cors = require('cors')
import express from "express";
import logger from 'morgan';
import cors from 'cors';

const contactsRouter = require('./routes/api/contacts')
import contactsRouter from './routes/api/contacts.js';

const app = express()

Expand All @@ -22,4 +22,4 @@ app.use((err, req, res, next) => {
res.status(500).json({ message: err.message })
})

module.exports = app
export default app;
152 changes: 145 additions & 7 deletions models/contacts.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,157 @@
// const fs = require('fs/promises')

const listContacts = async () => {}
import fs from 'node:fs/promises';
import path from 'node:path';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { readFile } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { writeFile } from 'node:fs/promises';
import { Buffer } from 'node:buffer';
import { error } from 'node:console';

const getContactById = async (contactId) => {}

const removeContact = async (contactId) => {}
const __dirname = dirname(fileURLToPath(import.meta.url));
// console.log(`Calea este :" ${__dirname }`);

const addContact = async (body) => {}
const contactsPath = `${__dirname}/contacts.json`;
// console.log(contactsPath);

const updateContact = async (contactId, body) => {}

module.exports = {
export async function listContacts() {
try {
const contents = await readFile(contactsPath, { encoding: "utf8" });
const contacts = JSON.parse(contents);
return contacts;

} catch (error) {
console.log("There is an error");
console.error(error);
}
};



export async function getContactById(contactId) {
try {
const contents = await readFile(contactsPath, { encoding: "utf8" });
const contacts = JSON.parse(contents);

const contact = contacts.find((contact) => contact.id === String(contactId));

if (contact) {
// console.table(contact);
return contact;
} else {
console.log(`Contact with ID ${contactId} not found.`);
}
} catch (error) {
console.log("There is an error");
console.error(error);
}
}


export async function addContact(contact) {
try {
const contents = await readFile(contactsPath, { encoding: "utf8" });
const contacts = JSON.parse(contents);
const newContactId = randomUUID();

const isValid = contact?.name && contact?.email && contact?.phone;
if (!isValid) {
throw new Error('The contact does not have all required parametres');
}

const newContact = {
id: newContactId,
...contact,
};
// console.dir(newContact);
contacts.push(newContact);
const parsedContact = JSON.stringify(contacts, null, 2);
await writeFile(contactsPath, parsedContact);


console.log('The contact has been ceated successfully !');
return newContact;


} catch (error) {
console.log("There is an error");
console.error(error);
}
}



export async function updateContact(updatedFields, contactId) {
try {
const contents = await readFile(contactsPath, { encoding: "utf8" });
const contacts = JSON.parse(contents);

// Găsim contactul după ID
const contactIndex = contacts.findIndex((contact) => contact.id === contactId);
if (contactIndex === -1) {
return null; // Contactul nu există
}

// Actualizam doar câmpurile specificate în body
const updatedContact = {
...contacts[contactIndex],
...updatedFields,
};
contacts[contactIndex] = updatedContact;

// Salvam modificările în fișier
await writeFile(contactsPath, JSON.stringify(contacts, null, 2));
return updatedContact; // Returnează contactul actualizat
} catch (error) {
console.error("There is an error", error);
throw error; // Aruncă eroarea pentru a fi gestionată de apelant
}
}





export async function removeContact(contactId) {
try {
const contents = await readFile(contactsPath, { encoding: "utf8" });
const contacts = JSON.parse(contents);

// Găsim contactul care trebuie șters
const contactIndex = contacts.findIndex((contact) => contact.id === String(contactId));
if (contactIndex === -1) {
console.log(`Contact with ID ${contactId} does not exist.`);
return null; // Returnează null dacă nu există
}

// Salvam contactul care urmează să fie șters
const removedContact = contacts[contactIndex];

// Filtrăm contactele
const updatedContacts = contacts.filter((contact) => contact.id !== String(contactId));
await writeFile(contactsPath, JSON.stringify(updatedContacts, null, 2));

console.log(`The contact with ID ${contactId} has been removed successfully!`);
console.table(updatedContacts);

// Returnează contactul șters
return removedContact;
} catch (error) {
console.error("There is an error", error);
throw error;
}
}


const contactsService = {
listContacts,
getContactById,
removeContact,
addContact,
updateContact,
}

export default contactsService;
38 changes: 34 additions & 4 deletions models/contacts.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,44 @@
},
{
"id": "e6ywwRe4jcqxXfCZOj_1e",
"name": "Thomas Lucas",
"email": "nec@Nulla.com",
"phone": "(704) 398-7993"
"name": "Marcus Lucas",
"email": "marc@Nulla.com",
"phone": "(700) 398-7993"
},
{
"id": "rsKkOQUi80UsgVPCcLZZW",
"name": "Alec Howard",
"email": "[email protected]",
"phone": "(748) 206-2688"
},
{
"id": "a70cff55-5c3a-4aa1-9c0d-77d12ed7bc55",
"name": "James Doe",
"email": "[email protected]",
"phone": "(705) 398-7993"
},
{
"id": "04546e12-4811-4154-859f-3f350a1af85b",
"name": "James Moon",
"email": "[email protected]",
"phone": "(711) 398-7993"
},
{
"id": "bcc8f110-2610-47fd-9f4f-080707fe8085",
"name": "Maria Calas",
"email": "[email protected]",
"phone": "(799) 398-7993"
},
{
"id": "466b28b7-4722-4ece-add7-fc2b15d961ed",
"name": "Joe Biden",
"email": "[email protected]",
"phone": "(711) 398-7981"
},
{
"id": "ab895d5a-1806-4b62-93f2-44fcedbb3223",
"name": "Joe Biden",
"email": "[email protected]",
"phone": "(712) 398-7981"
}
]
]
Loading