Proyecto: migración de funciones a clases
Curso de TypeScript: Programación Orientada a Objetos y Asincronismo
Contenido del curso
Juan David Reyes
ami me dice que todos los metodos de faker estan deprecados xd
Eder Ramirez
import { faker } from "@faker-js/faker";
Carlos Rodríguez
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); } }
Raycris Maldonado
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";
Diego Ivan Nacimiento
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
Diego Raciel Ortega Hernandez
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
Paul Francis
lo mismo me paso y solamente borre esas propiedades, ya me estaba desesperando por que me salía error
sidney.beltran
Carlos S. Aldazosa
Hay alguna ventaja de usar clase sobre funciones independientes? Aparte de la legibilidad?
Luis Ariza
La reusabilidad es otra ventaja, además de heredar a otras clases los mismos métodos(funciones).
Carlos S. Aldazosa
Cierto, muchas gracias!
Sebas Galvez
Gabriel Cordero
Muchas gracias, tu comentario me fue muy util!
Rafael Rodríguez Flores
Andrés Felipe Eslava Zuluaga
Josue Cerron Tuesta
Documentación de Faker
Alvaro Olarte
María Elena Correa Cano
3 meses después, pero la solución es agregar un ! justo después del index. De esta manera:
const prevData = this.products[index]!;
Esto ocurre porque Typescript se volvió más estricto y al agregar este '!' le estamos diciendo a Typescript: no te preocupes que te aseguro que no es undefined el id. He tenido múltiples errores en el curso gracias a que está desactualizado, pues Typescript ha cambiado considerablemente estos últimos años.
Espero haya sido de ayuda.
Denis Desiree Alvarez Camacho
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
Jhonnatan Diaz Valencia
Javier Mauricio Mora
Perdon la ignorancia, no he visto el otro curso, pero que difrencia existe entre el model y el dto?
Claudia Monica Peña Rubiano
Buen día, porque si Product es una interface no la implementan, sino la extienden, no entiendo ?
Christian Camilo Guzman Zapata
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
Mateo Andrés Piana
Mateo Andrés Piana
Perdón, puse el código dos veces 😁
David Fernando Torres Zapata
No entiendo el Omit y que es un dto, en el video no lo explica solo lo usa, alguien tiene idea de esto? Gracias ?
JJ RH
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.
Wilmer Nuñez
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:
Angel David Velasco Bonifaz
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'];}
Jonathan Gonzalez
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';
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); } }
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); } }
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); }; }
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); } }
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); }
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] } }