Aún no tienes acceso a esta clase

Crea una cuenta y continúa viendo este curso

Crear, editar y eliminar

14/25
Recursos

Aportes 14

Preguntas 6

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

El create quize hacerlo de la siguiente manera, y así créo un producto con las propiedades que quiero 👇… solo por seguridad 😉

create({ name, price, image }) {
  const product = {
    id: faker.datatype.uuid(),
    name,
    price,
    image,
  };
  this.products.push(product);
  return product;
}

Servicio Usuarios

Router Usuarios

Pueden usar el método map en el arreglo de productos para actualizarlos de manera más sencilla y hacerle un filter a los productos cuando vayan a hacer el delete. Les dejo un imagen con un pequeño ejemplo para que vean, ya ustedes pueden mejorarlo si quieren.

Realmente el codigo ha quedado mas hermoso luego de separar la logica en los distintos servicios

Ya superamos la mitad del curso y se me viene haciendo super rápido y ameno!

Tuve un problema para pasar los datos en el body del request. Estaba recibiendo undefined. Leyendo un poco, encontré que es necesario usar express.json()

Entiendo que es un middleware que se encarga de inyectar el body en el request.

Para usarlo, tienen que agregar la línea

app.use(express.json())

antes de donde inyectan el router en su aplicación

Para mis usuarios cree 3 métodos consultar, crear y eliminar, para crear la data con faker algo que encontré util es ir probando las diferentes opciones que tienen para generar contenido.
Este es mi código para el Servicio de los usuarios:

const faker = require('faker');

class UserService {
  constructor(){
    this.users = [];
    this.generate();
  }
  generate() {
    const limit = 5;
    for (let index = 0; index < limit; index++) {
      this.users.push({
        id: faker.datatype.uuid(),
        name: faker.name.firstName(),
        lastname: faker.name.lastName(),
        email: faker.internet.email(),
      });
    };
  };
  find() {
    return this.users;
  }
  create(data) {
    const newUser = {
      id: faker.datatype.uuid(),
      ...data
    };
    this.users.push(newUser);
    return newUser;
  };
  delete(id) {
    const index = this.users.findIndex(item => item.id === id);
    if (index === -1){
      throw new Error("product not found");
    }
    this.users.splice(index, 1);
    return {id};
  }
}

module.exports = UserService;

Agregué algunas mejoras para mantener la lógica de las validaciones fuera de los métodos donde se usan.

Agregué estos dos métodos:

validateIfExist (id) {
  const index = this.users.findIndex(item => item.id === id);
  if (index === -1) {
    throw new Error('User not found');
  }
}

validateIfNotExist (email) {
  const index = this.users.findIndex(item => item.email === email);
  if (index !== -1) {
    throw new Error('User exists');
    console.log(1);
    return false;
  }
}

Y luego los ocupo de la siguiente manera:

1 - Para validar si un usuario existe antes de crearlo usando el correo:

this.validateIfNotExist (email);

2 - Para validar si un usuario existe antes al buscarlo para mostrarlo, editarlo o eliminarlo:

this.validateIfExist (email);

Nota: mi ejemplo lo hice con usuarios a cambio de productos.

Min 1:38

Spread Operator, importantísimo y muy útil para concatenar arrays y objetos

categories.router.js

// imports of Modules
const express = require('express');
const CategoriesService = require('../services/categories.service');

// instace of class
const router = express.Router();
const service = new CategoriesService();

// routing
router.get("/", (req, res) => {
  const categories = service.find();
  res.status(200).json(categories);
})


router.get('/:id', (req, res) => {
  const id = req.params.id;
  const category = service.findOne(id);
  if(category){
    res.status(200).json(category);
  } else {
    res.status(404).json({
      message: 'Not Found'
    })
  }
})

router.post('/', (req, res) => {
  const body = req.body;
  const newCategory = service.create(body);
  res.status(201).json(newCategory);
})

router.patch('/:id', (req, res) => {
  const id = req.params.id;
  const body = req.body;
  const updataCategory = service.update(id, body);
  res.status(200).json(updataCategory);
})

router.delete('/:id', (req, res) => {
  const id = req.params.id;
  const deleteCategory = service.delete(id);
  res.status(200).json(deleteCategory);
})

module.exports = router;

categories.service.js

const faker = require('faker');

class CategoriesService {
  constructor(){
    this.categories = new Array();
    this.generate();
  }

  generate () {
    const count = 10;
    for (let i = 0; i < count; i++) {
      this.categories.push(
        {
          id: faker.datatype.uuid(),
          nombre: faker.commerce.department(),
          class: faker.commerce.productAdjective()
        }
      )
    }
  }

  create (data) {
    const newCategory = {
      id: faker.datatype.uuid(),
      ...data
    }
    this.categories.push(newCategory);
    return newCategory;
  }

  find(){
    return this.categories;
  }

  findOne (id) {
    return this.categories.find(item => item.id === id);
  }

  update (id, changes) {
    const index = this.categories.findIndex(item => item.id === id);
    if(index === -1) throw new Error('Ups, Not Found');
    const updataCategory = {
      ...this.categories[index],
      ...changes
    }
    this.categories[index] = updataCategory;
    return updataCategory;
  }

  delete (id) {
    const index = this.categories.findIndex(item => item.id === id);
    if(index === -1) throw new Error('Ups, Not Found');
    this.categories.splice(index, 1);
    return {
      delete: true
    }
  }
}


module.exports = CategoriesService;

Increíble curso, hasta ahora de los mejores que he tomado.

Solo me regresaba el precio y ya me había espantado pero no seguí viendo el video jaja

Esta es mi manera de hacer el update

// ProductsServices

update(id, data) {
        const { name, price, image } = data;
        const product = this.findOne(id);
        product.name = name || product.name;
        product.price = price || product.price;
        product.image = image || product.image;

        return product;
    }

//Product.Routes

router.patch('/:id', (req, res) => {
    const { id } = req.params;
    const body = req.body;
    const product = service.update(id, body);
    res.status(202).json({
        message: 'update',
        product,
    });
});

Lo que el profe hace en el delete es utilizar el Spread Syntax, una maravilla.
Aquí la documentación:
https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Spread_syntax

 const product = this.products[index];
    this.products[index] = {
      ... product,
      ... changes
    }
```;