A煤n no tienes acceso a esta clase

Crea una cuenta y contin煤a viendo este curso

Relaciones uno a muchos

20/33
Recursos

Aportes 3

Preguntas 3

Ordenar por:

驴Quieres ver m谩s aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesi贸n.

He creado dos snippets de VS Code para crear un Servicio y un Controller b谩sico mucho m谩s r谩pido. (para hacer lo que el profe hace en c谩mara r谩pida).

Para crearlos van a:

  • File
  • Preferences
  • User Snippets
  • Buscan typescript

En el archivo JSON que se les abri贸 copian este c贸digo dentro de las llaves:

  • Servicio
	"Create NestJS Service": {
		"prefix": "nest:s",
		"body": [
			"import { Injectable, NotFoundException } from '@nestjs/common';",
			"import { InjectRepository } from '@nestjs/typeorm';",
			"import { Repository } from 'typeorm';",
			"",
			"import { $2 } from '${1:entity-route}';",
			"import { ${4:createDto}, ${5:updateDto} } from '${3:dto-route}';",
			"",
			"@Injectable()",
			"export class ${6:serviceName}Service {",
			"  constructor(",
			"    @InjectRepository($2)",
			"    private ${7:repo}: Repository<$2>,",
			"  ) {}",
			"${0}",
			"  async findAll() {",
			"    return await this.$7.find();",
			"  }",
			"",
			"  async findOne(id: number) {",
			"    const ${8:object} = await this.$7.findOne(id);",
			"    if (!$8) throw new NotFoundException(`${9:object} not found.`);",
			"    return $8;",
			"  }",
			"",
			"  async create(data: $4) {",
			"    const ${10:newObject} = this.$7.create(data);",
			"    return await this.$7.save($10);",
			"  }",
			"",
			"  async update(id: number, changes: $5) {",
			"    const $8 = await this.findOne(id);",
			"    this.$7.merge($8, changes);",
			"    return await this.$7.save($8);",
			"  }",
			"",
			"  async remove(id: number) {",
			"    return await this.$7.delete(id);",
			"  }",
			"}",
		],
		"description": "This service has a basic CRUD implemented"
	},
  • Controller
"Create NestJS Controller": {
		"prefix": "nest:co",
		"body": [
			"import {",
			"  Controller,",
			"  Get,",
			"  Post,",
			"  Put,",
			"  Body,",
			"  Param,",
			"  Delete,",
			"  ParseIntPipe,",
			"} from '@nestjs/common';",
			"import { ApiTags } from '@nestjs/swagger';",
			"",
			"import { ${2:serviceName} } from '${1:service-route}';",
			"import { ${4:createDto}, ${5:updateDto} } from '${3:dto-route}';",
			"",
			"@ApiTags('${6:controllerName}')",
			"@Controller('$6')",
			"export class ${7:controllerNameInUppercase}Controller {",
			"  constructor(private ${8:serviceName}: $2) {}",
			"",
			"  @Get()",
			"  async findAll() {",
			"    return await this.$8.findAll();",
			"  }",
			"",
			"  @Get('/:id')",
			"  async getCategory(@Param('id') id: number) {",
			"    return await this.$8.findOne(id);",
			"  }",
			"",
			"  @Post()",
			"  async create(@Body() payload: $4) {",
			"    return await this.$8.create(payload);",
			"  }",
			"",
			"  @Put('/:id')",
			"  async update(",
			"    @Param('id', ParseIntPipe) id: number,",
			"    @Body() payload: $5,",
			"  ) {",
			"    return await this.$8.update(id, payload);",
			"  }",
			"",
			"  @Delete('/:id')",
			"  async remove(@Param('id', ParseIntPipe) id: number) {",
			"    return await this.$8.remove(id);",
			"  }",
			"}",
		],
		"description": "This controller has a basic CRUD implemented"
	}

Para usarlos simplemente tienen que crear su servicio/controlador normalmente y borrar lo que hay ah铆.
Luego simplemente ponen nest:s o nest:co y empiezan a llenar todos los datos que se pide.
Para avanzar solo precionen la tecla tab

Espero les sirva! 馃槂

Lo que vimos:

brand.entity.ts

import {
  PrimaryGeneratedColumn,
  Column,
  Entity,
  CreateDateColumn,
  UpdateDateColumn,
  OneToMany,
} from 'typeorm';
import { Product } from './product.entity';

@Entity()
export class Brand {
  @PrimaryGeneratedColumn()
  id: number;
  @Column({ type: 'varchar', length: 255, unique: true })
  name: string;

  @Column({ type: 'varchar', length: 255 })
  image: string;

  @CreateDateColumn({
    type: 'timestamptz',
    default: () => 'CURRENT_TIMESTAMP',
  })
  createAt: Date;

  @UpdateDateColumn({
    type: 'timestamptz',
    default: () => 'CURRENT_TIMESTAMP',
  })
  updateAt: Date;

  @OneToMany(() => Product, (product) => product.brand)
  products: Product;
}


brands.service.ts

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { Brand } from '../entities/brand.entity';
import { CreateBrandDto, UpdateBrandDto } from '../dtos/brand.dtos';

@Injectable()
export class BrandsService {
  constructor(@InjectRepository(Brand) private brandRepo: Repository<Brand>) {}
  findAll() {
    return this.brandRepo.find();
  }

  async findOne(id: number) {
    const product = await this.brandRepo.findOne(id);
    if (!product) {
      throw new NotFoundException(`Brand #${id} not found`);
    }
    return product;
  }

  create(data: CreateBrandDto) {
    const newBrand = this.brandRepo.create(data);
    return this.brandRepo.save(newBrand);
  }

  async update(id: number, changes: UpdateBrandDto) {
    const brand = await this.brandRepo.findOne(id);
    this.brandRepo.merge(brand, changes);
    return this.brandRepo.save(brand);
  }

  remove(id: number) {
    return this.brandRepo.delete(id);
  }
}

product.entity.ts

import {
  PrimaryGeneratedColumn,
  Column,
  Entity,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
} from 'typeorm';
import { Brand } from './brand.entity';

@Entity()
export class Product {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'varchar', length: 255, unique: true })
  name: string;

  @Column({ type: 'text' })
  description: string;

  @Column({ type: 'int' })
  price: number;

  @Column({ type: 'int' })
  stock: number;

  @Column({ type: 'varchar' })
  image: string;

  @CreateDateColumn({
    type: 'timestamptz',
    default: () => 'CURRENT_TIMESTAMP',
  })
  createAt: Date;

  @UpdateDateColumn({
    type: 'timestamptz',
    default: () => 'CURRENT_TIMESTAMP',
  })
  updateAt: Date;

  @ManyToOne(() => Brand, (brand) => brand.products)
  brand: Brand;
}

super chistoso escuchar la musica en 1.5x ademas de tener el volumen alto, llegu茅 a saltar jajaja

Excelente clase, cada d铆a aprendiendo mas sobre Manejo de bases de datos con nextjs lml