Proyecto: migración de funciones a clases
Clase 17 de 25 • Curso de TypeScript: Programación Orientada a Objetos y Asincronismo
Contenido del curso
Clase 17 de 25 • Curso de TypeScript: Programación Orientada a Objetos y Asincronismo
Contenido del curso
Juan David Reyes
Eder Ramirez
Carlos Rodríguez
Jeremias Villane
Miguel Ángel Tabares Cuadros
Raycris Maldonado
Diego Ivan Nacimiento
Diego Raciel Ortega Hernandez
Paul Francis
sidney.beltran
Carlos S. Aldazosa
Luis Ariza
Carlos S. Aldazosa
Sebas Galvez
Gabriel Cordero
Rafael Rodríguez Flores
Andrés Felipe Eslava Zuluaga
Josue Cerron Tuesta
Alvaro Olarte
Denis Desiree Alvarez Camacho
Jhonnatan Diaz Valencia
Javier Mauricio Mora
Claudia Monica Peña Rubiano
Christian Camilo Guzman Zapata
Mateo Andrés Piana
Mateo Andrés Piana
David Fernando Torres Zapata
JJ RH
Wilmer Nuñez
Angel David Velasco Bonifaz
Jonathan Gonzalez
ami me dice que todos los metodos de faker estan deprecados xd
import { faker } from "@faker-js/faker";
Desbes destructurar import { faker } no traerte todo el módulo
Les dejo el código compatible con la versión actual de faker y la versión actual de la api, que ahora sí contiene un createdAt y un updatedAt:
import { faker } from '@faker-js/faker'; import { CreateProductDto, UpdateProductDto } from '../dtos/product.dto'; import { Product } from '../models/product.model'; export class ProductMemoryService { private products: Product[] = []; create(data: CreateProductDto): Product { const newProduct = { ...data, id: faker.number.int(), createdAt: faker.date.recent(), updatedAt: faker.date.recent(), category: { id: data.categoryId, name: faker.commerce.department(), image: faker.image.url(), createdAt: faker.date.recent(), updatedAt: faker.date.recent(), }, }; return this.add(newProduct); } add(product: Product) { this.products.push(product); return product; } update = (id: Product['id'], data: UpdateProductDto): Product => { const index = this.products.findIndex((item) => item.id === id); const prevData = this.products[index]; this.products[index] = { ...prevData, ...data, }; return this.products[index]; }; findOne(id: Product['id']) { return this.products.find((item) => item.id === id); } }
Toma tu like buen hombre, querido salvavidas
Si todo lo relacionado con Faker les da error, deben de utlizar el nombre de faker entre llaves. así
import { faker } from "@faker-js/faker";
Creo que al método add debería hacerlo privado, así no se puede acceder desde fuera de la clase. Ya que su finalidad es ser utilizado internamente por el método create
Me tarde un rato en saber por que me daba error el metodo "create" era por que tenia creationAt y UpdatedAt en las propiedades de la interfaz Product y Category
lo mismo me paso y solamente borre esas propiedades, ya me estaba desesperando por que me salía error
Codigo actualizado:
import { faker } from '@faker-js/faker'; import { Product } from '../models/product.model'; import { CreateProductDto, UpdateProductDto } from '../DTOs/product.dto'; export class ProductMemoryService { private products: Product[] = []; create(data: CreateProductDto): Product { const newProduct: Product = { ...data, id: faker.number.int(), creationAt: faker.date.recent(), updatedAt: faker.date.recent(), slug: faker.image.url(), images: [faker.image.url(), faker.image.url()], category: { id: data.categoryId, name: faker.commerce.department(), slug: faker.image.url(), image: faker.image.url(), creationAt: faker.date.recent(), updatedAt: faker.date.recent(), }, }; this.products.push(newProduct); return this.add(newProduct); } add(product: Product) { this.products.push(product); return product; } UpdateProductDto(id: Product['id'], changes: UpdateProductDto): Product { const index = this.products.findIndex((item) => item.id === id); const prevData = this.products[index]; this.products[index] = { ...prevData, ...changes, }; return this.products[index]; } findOne(id: Product['id']) { return this.products.find((item) => item.id === id); } }
Hay alguna ventaja de usar clase sobre funciones independientes? Aparte de la legibilidad?
La reusabilidad es otra ventaja, además de heredar a otras clases los mismos métodos(funciones).
Cierto, muchas gracias!
import { faker } from '@faker-js/faker'; import { Product } from '../models/product.model'; import { CreateProductDto, updateProductDto } from '../dtos/product.dto'; export class ProductMemoryService { private products: Product[] = []; create(data: CreateProductDto): Product { const newProduct = { ...data, id: faker.datatype.number(), category: { id: data.categoryId, name: faker.commerce.department(), image: faker.image.imageUrl(), }, }; this.products.push(newProduct); return this.add(newProduct); } add(product: Product) { this.products.push(product); return product; } updateProduct(id: Product['id'], changes: updateProductDto): Product { const index = this.products.findIndex((item) => item.id === id); const prevData = this.products[index]; this.products[index] = { ...prevData, ...changes, }; return this.products[index]; } findOne(id: Product['id']) { return this.products.find((item) => item.id === id); } }
Muchas gracias, tu comentario me fue muy util!
Hay un pequeño error amigo. En el método update, se coló una minúscula:
changes: ++U++pdateProductDto)
updateProduct(id: Product['id'], changes: UpdateProductDto): Product { const index = this.products.findIndex((item) => item.id === id); const prevData = this.products[index]; this.products[index] = { ...prevData, ...changes, }; return this.products[index]; }
Migración de mi códig:
import { faker } from '@faker-js/faker'; import { Product } from "../models/product.model"; import { CreateProductDto, UpdateProductDto } from "../dtos/product.dto"; import { Category } from '../models/category.model'; export class ProductMemoryService { private products: Product[] = []; create (data: CreateProductDto): Product { const newProduct = { ...data, id: faker.datatype.number(), category: { id: data.categoryId, createdAt: faker.date.past(5), name: faker.commerce.department(), image: faker.image.imageUrl() }, }; return this.add(newProduct); }; add (product: Product) { this.products.push(product); return product; }; update (id: number, changes: UpdateProductDto): Product { const index = this.products.findIndex(item => item.id === id); const prevData = this.products[index]; this.products[index] = { ...prevData, ...changes, } return this.products[index]; }; delete (id: number) { const getIndexOfProduct = (id: Category['id']) => this.products.findIndex(item => item.id === id); const index: number = getIndexOfProduct(id); this.products.splice(index, 1); console.log(this.products); }; getOne (id: number) { return this.products.find(item => item.id === id); }; }
Documentación de Faker
A mi el product-memory.service.ts elmetodo update me estaba arrojando el siguiente error:
Type 'Product | undefined' is not assignable to type 'Product'. Type 'undefined' is not assignable to type 'Product'.ts
De acuerdo al error para asigmarlo al this.products[index] lo ajuste asi, pero no si esta bien:
import { faker } from '@faker-js/faker'; import { Product } from '../models/product.model'; import { CreateProductDto, UpdateProductDto } from '../dtos/product.dto'; export class ProductMemoryService{ private products: Product[] = []; create(data: CreateProductDto): Product { const newProduct = { ...data, id: faker.number.int(), category: { id: data.categoryId, name: faker.commerce.department(), image: faker.image.url(), slug: faker.helpers.slugify(faker.commerce.department()), createdAt: faker.date.recent(), updatedAt: faker.date.recent(), } } return this.add(newProduct); } add(product: Product) { this.products.push(product); return product; } update(id: Product['id'], changes: UpdateProductDto ): Product { const index = this.products.findIndex(item => item.id === id); const prevData = this.products[index]; const updatedProduct: Product = { ...prevData, ...changes } as Product; this.products[index] = updatedProduct; return this.products[index]; } findOne(id: Product['id']) { return this.products.find(item => item.id === id); } }
Hola. Buenas tardes. En mi caso me da este error. Property 'number' does not exist on type 'DatatypeModule'. Quisiera saber como lo puedo resolver... Gracias
El error puede ser por la versión del faker, yo lo solucioné así:
create(data: CreateProductDto): Product { const newProduct = { ...data, id: faker.number.int(), category: { id: data.categoryId, name: faker.commerce.department(), image: faker.image.url() } } return this.add(newProduct); } ```create(data: CreateProductDto): Product { const newProduct = { ...data, id: faker.number.int(), category: { id: data.categoryId, name: faker.commerce.department(), image: faker.image.url() } } return this.add(newProduct); }
Perdon la ignorancia, no he visto el otro curso, pero que difrencia existe entre el model y el dto?
Buen día, porque si Product es una interface no la implementan, sino la extienden, no entiendo ?
Esta clase me dejo muy perdido, toco cosas de otro curso y las puso ahi sin mas, en vez de tomarse el tiempo y crearlas explicando por que esta creando las cosas en vez de solucionar los conflictos que genero
Me parece más lógica que el método "create" sea privado y el método "add" sea quien lo llame y esté público.private create(data: CreateProductDto): Product { const newProduct = { ...data, id: faker.datatype.number(), creationAt: faker.date.recent(), category: { id: data.categoryId, name: faker.commerce.department(), creationAt: faker.date.recent(), updatedAt: faker.date.recent(), image: faker.image.imageUrl() } } return newProduct; } add(data: CreateProductDto): Product { const newProduct = this.create(data) this._products.push(newProduct); return newProduct; }
import faker from '@faker-js/faker'; import { Product } from './product.model'; import { CreateProductDto, UpdateProductDto } from './product.dto'; export class ProductsMemoryService { private _products: Product[] = [] private create(data: CreateProductDto): Product { const newProduct = { ...data, id: faker.datatype.number(), creationAt: faker.date.recent(), category: { id: data.categoryId, name: faker.commerce.department(), creationAt: faker.date.recent(), updatedAt: faker.date.recent(), image: faker.image.imageUrl() } } return newProduct; } add(data: CreateProductDto): Product { const newProduct = this.create(data) this._products.push(newProduct); return newProduct; } update = (id: Product['id'], changes: UpdateProductDto): Product => { const index = this._products.findIndex(item => item.id === id); const prevData = this._products[index]; this._products[index] = { ...prevData, ...changes } return this._products[index]; } findOne(id: Product["id"]): Product { const index = this._products.findIndex(item => item.id === id); if (index === -1) throw new Error("Not found product by id") return this._products[index] } }
Perdón, puse el código dos veces 😁
No entiendo el Omit y que es un dto, en el video no lo explica solo lo usa, alguien tiene idea de esto? Gracias ?
Eso es parte de otro curso.
velo antes de seguir con el de POO: Curso de TypeScript: Tipos Avanzados y Funciones - Platzi
y antes de Tipos Avanzados y Funciones va: Curso de Fundamentos de TypeScript - Platzi
porque si no los ves en el orden vas a estar perdido todo el tiempo.
A quienes les aparezca un error respecto al import de faker, les recomiendo lo siguiente:
npm install --save-dev @faker-js/fakerimport { faker } from '@faker-js/faker';Para mayor información visitar la web oficial:
Hay cambios con faker, se debe de instalar como dependencia import { faker } from '@faker-js/faker';create (data: CreateProductDto) : Product { const newProduct = { id: faker.number.int(), creationAt: new Date(), updatedAt: new Date(), category: { id: data.categoryId, name: faker.commerce.department(), image: faker.image.urlPicsumPhotos(), creationAt: new Date(), updatedAt: new Date(), }, ...data, } return this.add(newProduct); }js npm install @faker-js/faker --save-dev y se debe importar de este modo ```js
import { faker } from '@faker-js/faker';
```js create (data: CreateProductDto) : Product { const newProduct = { id: faker.number.int(), creationAt: new Date(), updatedAt: new Date(), category: { id: data.categoryId, name: faker.commerce.department(), image: faker.image.urlPicsumPhotos(), creationAt: new Date(), updatedAt: new Date(), }, ...data, } return this.add(newProduct); } ```y omitirlos en los dtos ```js export interface CreateProductDto extends Omit<Product, 'id' | 'creationAt'| 'updatedAt' | 'category'> { categoryId: Category['id']; } ```export interface CreateProductDto extends Omit\<Product, 'id' | 'creationAt'| 'updatedAt' | 'category'> { categoryId: Category\['id'];}
Aqui esta mi version de la function create(). Use los metodos de la version mas reciente de faker
create(data: CreateProductDto): Product { const newProduct = { ...data, id: faker.number.int(), category: { id: data.categoryId, name: faker.commerce.department(), image: faker.image.url() } } return this.add(newProduct); }
Tambien cambie el importe de faker:
import { faker } from '@faker-js/faker';