Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

StackOverflow Point

StackOverflow Point Navigation

  • Web Stories
  • Badges
  • Tags
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Web Stories
  • Badges
  • Tags
Home/ Questions/Q 3680
Alex Hales
  • 0
Alex HalesTeacher
Asked: June 2, 20222022-06-02T22:56:31+00:00 2022-06-02T22:56:31+00:00

javascript – How to pass my products array that is inside my req.body to objects to be able to obtain them through dot notation in the POST in models/cart.js?

  • 0

[ad_1]

I was trying to use map but there is no way for me to take the data from the models/cart.js to my controllers/cart.js, basically I need an alternative to be able to enter the data inside my req.body.products through object notation (products is an array).

[models/cart.js]

const fs = require("fs").promises;
const { customAlphabet } = require("nanoid");
const nanoid = customAlphabet("1234567890", 5);

class Cart {
  constructor(txtNameFile) {
    this.txtNameFile = txtNameFile;
    this.dataCart = [];
  }

  async fileInJSON() {
    let fileTxt = await fs.readFile(this.txtNameFile, "utf-8");
    let type = JSON.parse(fileTxt);
    return type;
  }

  async fileSaving(item) {
    let type = JSON.stringify(item);
    await fs.writeFile(this.txtNameFile, type);
  }

  async createCart(data) {
    try {
      const cart = await this.fileInJSON();
      const newCart = {
        id: Number(nanoid()),
        date: new Date().toLocaleString(),
        products: [
          {
            id: Number(nanoid()),
            title: data.products[0].title,
            price: Number(data.products[0].price),
            image: data.products[0].image,
            description: data.products[0].description,
            stock: data.products[0].stock,
            date: new Date().toLocaleString(),
            code: data.products[0].code,
          },
        ],
      };
      cart.push(newCart);
      await this.fileSaving(cart);

      return newCart;
    } catch (error) {
      console.log(error);
    }
  }

  async deleteCart(id) {
    try {
      const cart = await this.fileInJSON();
      const newCart = cart.filter((cart) => cart.id !== Number(id));
      await this.fileSaving(newCart);
      return newCart;
    } catch (error) {
      console.log(error);
    }
  }

  async getProductsInCart(id) {
    try {
      const cart = await this.fileInJSON();
      const productos = cart.find((cart) => cart.id === Number(id));
      return productos;
    } catch (error) {
      console.log(error);
    }
  }

  // GET in endpoint  /:id/products

  // POST in endpoint  /:id/products
  async addProduct(id, data) {
    try {
      const cart = await this.fileInJSON();
      const newCart = cart.map((cart) => {
        if (cart.id === Number(id)) {
          cart.products.push({
            id: data.id,
            title: data.title,
            price: Number(data.price),
            image: data.image,
            description: data.description,
            stock: data.stock,
            date: new Date().toLocaleString(),
            code: data.code,
          });
        }
        return cart;
      });
      await this.fileSaving(newCart);
      return newCart;
    } catch (error) {
      console.log(error);
    }
  }

  // DELETE in endpoint  /:id/products/:id_prod

  async deleteEntireProduct(id, id_prod) {
    try {
      const cart = await this.fileInJSON();
      const newCart = cart.map((cart) => {
        if (cart.id === Number(id)) {
          cart.products = cart.products.filter(
            (product) => product.id !== Number(id_prod)
          );
        }
        return cart;
      });
      await this.fileSaving(newCart);
      return newCart;
    } catch (error) {
      console.log(error);
    }
  }

  // try {
  //   const cart = await this.fileInJSON();
  //   const newCart = {
  //     id: Number(nanoid()),
  //     timeStamp: new Date().toLocaleString(),
  //     products: data.products,
  //   };

  //   cart.items.push(newCart);
  //   await this.fileSaving(cart);
  //   return newCart;
  // } catch (error) {
  //   console.log(error);
  // }
}
module.exports = Cart;

[controllers/cart.js]

const Cart = require("../models/cart");
const carrito = new Cart("cart.json");
const { customAlphabet } = require("nanoid");
const nanoid = customAlphabet("1234567890", 5);

const creatingCartsWithProducts = async (req, res) => {
  const newCart = await carrito.createCart(req.body);
  return res.json(newCart);
};

const listOfProducts = async (req, res) => {
  const carts = carrito.getProductsInCart(req.params.id);
  return res.json(await carts);
};

module.exports = {
  creatingCartsWithProducts,
  listOfProducts,
};

[routes/cart.js]

const express = require("express");
const router = express.Router();
const { creatingCartsWithProducts, listOfProducts } = require("../controllers/cart");

router.post("/", creatingCartsWithProducts);
router.get("/:id/productos", listOfProducts);

module.exports = router;

[cart.json]

[
  {
    "id": 63589,
    "date": "6/2/2022, 7:04:05 PM",
    "products": [
      {
        "title": "Producto NsiiiiiiIKE TIKETIT",
        "price": 5500,
        "image": "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.pinterest.com%2Fpin%2F569098989827098984%2F&psig=AOvVaw2X_Z_7Z_X_Z_X_X_Z_X_&ust=1548790984533000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKDqx-_3-4CFQAAAAAdAAAAABAD",
        "description": "Descripcion del producto 3",
        "stock": 20,
        "date": "6/2/2022, 7:04:05 PM",
        "code": "5ABBE5"
      }
    ]
  }
]

[ad_2]

  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report
Leave an answer

Leave an answer
Cancel reply

Browse

Sidebar

Ask A Question

Related Questions

  • xcode - Can you build dynamic libraries for iOS and ...

    • 0 Answers
  • bash - How to check if a process id (PID) ...

    • 8057 Answers
  • database - Oracle: Changing VARCHAR2 column to CLOB

    • 1842 Answers
  • What's the difference between HEAD, working tree and index, in ...

    • 1924 Answers
  • Amazon EC2 Free tier - how many instances can I ...

    • 0 Answers

Stats

  • Questions : 43k

Subscribe

Login

Forgot Password?

Footer

Follow

© 2022 Stackoverflow Point. All Rights Reserved.

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.