I’m having trouble transforming JSON into JS code in this exercise someone gave me. It involves utilizing FileSystem to store an array of products.
I tried to store an array of products to a file via FileSystem and successfully did so, but the class method returns JSON code instead of JS code even though I think I parsed it correctly.
Also, If someone has any idea how I could make a private class method that generates an ID automatically as an accumulator for any product that is created, I’d highly appreciate it!
Anything helps! Thanks in advance!
const fs = require('fs')
class ProductManager {
constructor() {
this.path = './products.json'
}
async addProduct(title, description, price, thumb, stock) {
try {
const product = {
title,
description,
price,
thumb,
//FIXME: id: this.#generateId() + 1,
stock
};
const productsFile = await this.getProducts();
productsFile.push(product)
await fs.promises.writeFile(this.path, JSON.stringify(productsFile));
} catch (err) { console.log(err) }
}
// async deleteProduct(id) {
// try {
// if (this.path.find((product) => product.id === id)) return this.path.find((product) => product.id === id)
// else return `Error: Could not find product with specified ID (ID: ${id})`
// } catch (err) { console.log(err) }
// }
//FIXME:
async #generateId() {
try {
let newId = 0;
this.path.map((product) => {
if (product.id > newId) newId = product.id;
});
return newId;
} catch (err) { console.log(err) }
}
async getProducts() {
try {
if (fs.existsSync(this.path)) {
const products = await fs.promises.readFile(this.path, 'utf-8')
const productsJS = JSON.parse(products)
return productsJS
} else { return [] }
} catch (err) { console.log(err) }
}
// async getProductById(id) {
// try {
// if (this.path.find((product) => product.id === id)) return await this.path.find((product) => product.id === id)
// else return `Error: Could not find product with specified ID (ID: ${id})`
// } catch (err) { console.log(err) }
// }
}
const productManager = new ProductManager
const execution = async () => {
const get1 = await productManager.getProducts();
console.log('1st Get: ' + get1);
await productManager.addProduct('Remera', 'Remerita bien facherita', 7500, 'urlgenerica', 50);
await productManager.addProduct('Pantalon', 'Pantaloncito bien facherito', 12500, 'urlgenerica2', 70);
await productManager.addProduct('Gorra Messi', 'Gorrita del Messias bien mundialista', 181222, 'urlgenerica3', 1);
const get2 = await productManager.getProducts();
console.log('2nd Get: ' + get2);
}
execution()