From 18324968dcede8bdf53aab143d408de0ed595b3a Mon Sep 17 00:00:00 2001 From: Gustavo Rezende Date: Sat, 7 Dec 2024 18:49:15 -0300 Subject: [PATCH 1/5] Aula 1 --- README.md | 11 ----- package.json | 11 +++++ src/assets/productManager.js | 81 ++++++++++++++++++++++++++++++++++++ src/index.js | 1 + 4 files changed, 93 insertions(+), 11 deletions(-) delete mode 100644 README.md create mode 100644 package.json create mode 100644 src/assets/productManager.js create mode 100644 src/index.js diff --git a/README.md b/README.md deleted file mode 100644 index 07fd982..0000000 --- a/README.md +++ /dev/null @@ -1,11 +0,0 @@ -

Material referente as entregas dos desafios no curso de Back-End na Coderhouse Brasil

- -
- -

Aulas com entrega:

- - -Acesse as aulas pelas branches \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..5425b6b --- /dev/null +++ b/package.json @@ -0,0 +1,11 @@ +{ + "name": "cursocoderhousebackend", + "version": "1.0.0", + "description": "aula 1 de back end", + "main": "productManager.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "Gustavo Rezende", + "license": "ISC" +} diff --git a/src/assets/productManager.js b/src/assets/productManager.js new file mode 100644 index 0000000..a9e0cb6 --- /dev/null +++ b/src/assets/productManager.js @@ -0,0 +1,81 @@ +class ProductManager { + constructor() { + this.products = []; + this.currentId = 1; + } + + addProduct({ title, description, price, thumbnail, code, stock }) { + // Verification + if (!title || !description || !price || !thumbnail || !code || !stock) { + console.error("Error: All field are required."); + return; + } + + // Verification + if (this.products.some((product) => product.code === code)) { + console.error(`Error: The code "${code}" already in use.`); + return; + } + + // Create + const newProduct = { + id: this.currentId++, + title, + description, + price, + thumbnail, + code, + stock, + }; + + // Add List + this.products.push(newProduct); + console.log(`Product "${title}" added successfully.`); + } + + getProductById(id) { + const product = this.products.find((product) => product.id === id); + if (!product) { + console.error("Error: Product not found."); + return; + } + return product; + } + } + + // Test + const manager = new ProductManager(); + + // Add product + manager.addProduct({ + title: "Product 1", + description: "Product description 1", + price: 100, + thumbnail: "product1.jpg", + code: "P001", + stock: 10, + }); + + manager.addProduct({ + title: "Product 2", + description: "Product description 2", + price: 150, + thumbnail: "product2.jpg", + code: "P002", + stock: 5, + }); + + // Try to add product with repeated code + manager.addProduct({ + title: "Product 3", + description: "Product description 3", + price: 200, + thumbnail: "product3.jpg", + code: "P001", + stock: 8, + }); + + // Search product by ID + console.log(manager.getProductById(1)); // Should return Product 1 + console.log(manager.getProductById(3)); // Should return "Error: Product not found" + \ No newline at end of file diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..03576ed --- /dev/null +++ b/src/index.js @@ -0,0 +1 @@ +// 404 \ No newline at end of file From 4def2941cb039cd0d177b947419aae12a98b95df Mon Sep 17 00:00:00 2001 From: Gustavo Rezende Date: Thu, 12 Dec 2024 21:20:18 -0300 Subject: [PATCH 2/5] aula4 --- aula/default.js | 32 ++++++++++++++ package.json | 2 +- src/assets/productManager.js | 81 ------------------------------------ 3 files changed, 33 insertions(+), 82 deletions(-) create mode 100644 aula/default.js diff --git a/aula/default.js b/aula/default.js new file mode 100644 index 0000000..635c78d --- /dev/null +++ b/aula/default.js @@ -0,0 +1,32 @@ +const fs = require('fs').promises; +class ManagerUsers{ + constructor(){ + this.filePath = 'Usuarios.json'; + } + async CriarUsuario(usuario){ + try{ + const camposRequeridos =['nome','sobrenome','idade','curso']; + for (const campo of camposRequeridos){ + if(!(campo in usuario)){ + throw new Error(`Campo obrigatorio ausente: ${campo}`); + } + } + } + + let usuarios= []; + + try{ + const data = await fs.readFile(this.filePath, 'utf8'); + usuarios = JSON.parse(data); + } catch(error){ + if (error.code ==='ENOENT'){ + usuarios=[] + }else{ + throw error; + } + } + usuarios.push(usuario); + await fs.writeFile(this.filePath,JSON.stringify(usuarios,null,2)); + return usuario; + } +} \ No newline at end of file diff --git a/package.json b/package.json index 5425b6b..7aeafda 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "cursocoderhousebackend", "version": "1.0.0", - "description": "aula 1 de back end", + "description": "aula 4 de back end", "main": "productManager.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" diff --git a/src/assets/productManager.js b/src/assets/productManager.js index a9e0cb6..e69de29 100644 --- a/src/assets/productManager.js +++ b/src/assets/productManager.js @@ -1,81 +0,0 @@ -class ProductManager { - constructor() { - this.products = []; - this.currentId = 1; - } - - addProduct({ title, description, price, thumbnail, code, stock }) { - // Verification - if (!title || !description || !price || !thumbnail || !code || !stock) { - console.error("Error: All field are required."); - return; - } - - // Verification - if (this.products.some((product) => product.code === code)) { - console.error(`Error: The code "${code}" already in use.`); - return; - } - - // Create - const newProduct = { - id: this.currentId++, - title, - description, - price, - thumbnail, - code, - stock, - }; - - // Add List - this.products.push(newProduct); - console.log(`Product "${title}" added successfully.`); - } - - getProductById(id) { - const product = this.products.find((product) => product.id === id); - if (!product) { - console.error("Error: Product not found."); - return; - } - return product; - } - } - - // Test - const manager = new ProductManager(); - - // Add product - manager.addProduct({ - title: "Product 1", - description: "Product description 1", - price: 100, - thumbnail: "product1.jpg", - code: "P001", - stock: 10, - }); - - manager.addProduct({ - title: "Product 2", - description: "Product description 2", - price: 150, - thumbnail: "product2.jpg", - code: "P002", - stock: 5, - }); - - // Try to add product with repeated code - manager.addProduct({ - title: "Product 3", - description: "Product description 3", - price: 200, - thumbnail: "product3.jpg", - code: "P001", - stock: 8, - }); - - // Search product by ID - console.log(manager.getProductById(1)); // Should return Product 1 - console.log(manager.getProductById(3)); // Should return "Error: Product not found" - \ No newline at end of file From 93e4c93590bf597a88fbe4f61e7e6b76d2a01a3d Mon Sep 17 00:00:00 2001 From: Gustavo Rezende Date: Thu, 12 Dec 2024 21:31:23 -0300 Subject: [PATCH 3/5] . --- src/assets/productManager.js | 75 ++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/src/assets/productManager.js b/src/assets/productManager.js index e69de29..08a16c9 100644 --- a/src/assets/productManager.js +++ b/src/assets/productManager.js @@ -0,0 +1,75 @@ +const fs = require('fs'); + +class ProductManager { + constructor(path) { + this.path = path; + } + + async addProduct(product) { + try { + const products = await this.getProducts(); + const newId = products.length > 0 ? products[products.length - 1].id + 1 : 1; + const newProduct = { id: newId, ...product }; + products.push(newProduct); + await fs.promises.writeFile(this.path, JSON.stringify(products, null, 2)); + return newProduct; + } catch (error) { + throw new Error('Erro ao adicionar produto: ' + error.message); + } + } + + async getProducts() { + try { + if (!fs.existsSync(this.path)) { + await fs.promises.writeFile(this.path, JSON.stringify([])); + return []; + } + const data = await fs.promises.readFile(this.path, 'utf-8'); + return JSON.parse(data); + } catch (error) { + throw new Error('Erro ao obter produtos: ' + error.message); + } + } + + async getProductById(id) { + try { + const products = await this.getProducts(); + const product = products.find((p) => p.id === id); + return product || null; + } catch (error) { + throw new Error('Erro ao buscar produto: ' + error.message); + } + } + + async updateProduct(id, updates) { + try { + const products = await this.getProducts(); + const productIndex = products.findIndex((p) => p.id === id); + if (productIndex === -1) { + throw new Error(`Produto com ID ${id} não encontrado`); + } + products[productIndex] = { ...products[productIndex], ...updates }; + await fs.promises.writeFile(this.path, JSON.stringify(products, null, 2)); + return products[productIndex]; + } catch (error) { + throw new Error('Erro ao atualizar produto: ' + error.message); + } + } + + async deleteProduct(id) { + try { + const products = await this.getProducts(); + const filteredProducts = products.filter((p) => p.id !== id); + if (products.length === filteredProducts.length) { + throw new Error(`Produto com ID ${id} não encontrado`); + } + await fs.promises.writeFile(this.path, JSON.stringify(filteredProducts, null, 2)); + return `Produto com ID ${id} removido com sucesso.`; + } catch (error) { + throw new Error('Erro ao deletar produto: ' + error.message); + } + } +} + +module.exports = ProductManager; + From 54d2af3cf10e254d56b16ece2e8d1087ccc6a467 Mon Sep 17 00:00:00 2001 From: Gustavo Rezende Date: Wed, 26 Feb 2025 16:43:07 -0300 Subject: [PATCH 4/5] att --- README.md | 0 aula/default.js | 32 -------------------------------- 2 files changed, 32 deletions(-) create mode 100644 README.md delete mode 100644 aula/default.js diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/aula/default.js b/aula/default.js deleted file mode 100644 index 635c78d..0000000 --- a/aula/default.js +++ /dev/null @@ -1,32 +0,0 @@ -const fs = require('fs').promises; -class ManagerUsers{ - constructor(){ - this.filePath = 'Usuarios.json'; - } - async CriarUsuario(usuario){ - try{ - const camposRequeridos =['nome','sobrenome','idade','curso']; - for (const campo of camposRequeridos){ - if(!(campo in usuario)){ - throw new Error(`Campo obrigatorio ausente: ${campo}`); - } - } - } - - let usuarios= []; - - try{ - const data = await fs.readFile(this.filePath, 'utf8'); - usuarios = JSON.parse(data); - } catch(error){ - if (error.code ==='ENOENT'){ - usuarios=[] - }else{ - throw error; - } - } - usuarios.push(usuario); - await fs.writeFile(this.filePath,JSON.stringify(usuarios,null,2)); - return usuario; - } -} \ No newline at end of file From e7e1e8d354fa5a7f7f316c52a874480b5ffb9306 Mon Sep 17 00:00:00 2001 From: Gustavo Rezende Date: Wed, 26 Feb 2025 16:57:56 -0300 Subject: [PATCH 5/5] done --- README.md | 5 ++ src/assets/productManager.js | 118 +++++++++++++++++------------------ 2 files changed, 64 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index e69de29..c4aa258 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,5 @@ +

Descrição:

+
+
+

12/12/2024 Desafio ( Gestão de Arquivos em Javascript ) da Aula 4 ( Introdução ao Node.js ) do curso de Back-end na CoderHouse; Turma #63515 de 2024/25.

+
\ No newline at end of file diff --git a/src/assets/productManager.js b/src/assets/productManager.js index 08a16c9..d27dbe4 100644 --- a/src/assets/productManager.js +++ b/src/assets/productManager.js @@ -1,75 +1,75 @@ const fs = require('fs'); class ProductManager { - constructor(path) { - this.path = path; - } + constructor(path) { + this.path = path; + } - async addProduct(product) { - try { - const products = await this.getProducts(); - const newId = products.length > 0 ? products[products.length - 1].id + 1 : 1; - const newProduct = { id: newId, ...product }; - products.push(newProduct); - await fs.promises.writeFile(this.path, JSON.stringify(products, null, 2)); - return newProduct; - } catch (error) { - throw new Error('Erro ao adicionar produto: ' + error.message); + async addProduct(product) { + let products = await this.getProducts(); + const newProduct = { + id: products.length > 0 ? products[products.length - 1].id + 1 : 1, + ...product + }; + products.push(newProduct); + await fs.promises.writeFile(this.path, JSON.stringify(products, null, 2)); + return newProduct; } - } - async getProducts() { - try { - if (!fs.existsSync(this.path)) { - await fs.promises.writeFile(this.path, JSON.stringify([])); - return []; - } - const data = await fs.promises.readFile(this.path, 'utf-8'); - return JSON.parse(data); - } catch (error) { - throw new Error('Erro ao obter produtos: ' + error.message); + async getProducts() { + try { + const data = await fs.promises.readFile(this.path, 'utf-8'); + return JSON.parse(data); + } catch (error) { + return []; + } } - } - async getProductById(id) { - try { - const products = await this.getProducts(); - const product = products.find((p) => p.id === id); - return product || null; - } catch (error) { - throw new Error('Erro ao buscar produto: ' + error.message); + async getProductById(id) { + const products = await this.getProducts(); + return products.find(product => product.id === id) || null; } - } - async updateProduct(id, updates) { - try { - const products = await this.getProducts(); - const productIndex = products.findIndex((p) => p.id === id); - if (productIndex === -1) { - throw new Error(`Produto com ID ${id} não encontrado`); - } - products[productIndex] = { ...products[productIndex], ...updates }; - await fs.promises.writeFile(this.path, JSON.stringify(products, null, 2)); - return products[productIndex]; - } catch (error) { - throw new Error('Erro ao atualizar produto: ' + error.message); + async updateProduct(id, updatedFields) { + let products = await this.getProducts(); + let productIndex = products.findIndex(product => product.id === id); + + if (productIndex === -1) { + return null; + } + + products[productIndex] = { ...products[productIndex], ...updatedFields, id }; + await fs.promises.writeFile(this.path, JSON.stringify(products, null, 2)); + return products[productIndex]; } - } - async deleteProduct(id) { - try { - const products = await this.getProducts(); - const filteredProducts = products.filter((p) => p.id !== id); - if (products.length === filteredProducts.length) { - throw new Error(`Produto com ID ${id} não encontrado`); - } - await fs.promises.writeFile(this.path, JSON.stringify(filteredProducts, null, 2)); - return `Produto com ID ${id} removido com sucesso.`; - } catch (error) { - throw new Error('Erro ao deletar produto: ' + error.message); + async deleteProduct(id) { + let products = await this.getProducts(); + const filteredProducts = products.filter(product => product.id !== id); + + if (products.length === filteredProducts.length) { + return false; + } + + await fs.promises.writeFile(this.path, JSON.stringify(filteredProducts, null, 2)); + return true; } - } } -module.exports = ProductManager; +//! Execution +(async () => { + const manager = new ProductManager('products.json'); + + await manager.addProduct({ + title: 'Produto Exemplo', + description: 'Descrição do produto', + price: 100, + thumbnail: 'imagem.jpg', + code: 'ABC123', + stock: 10 + }); + + console.log(await manager.getProducts()); +})(); +