Importante

jueves, 11 de mayo de 2023

nest servicios

 los servicios se unen a las cotroladores  y se generan pior 

 nest g s nombre_del_servicio

ejemplo: 

 nest g s twits

el resultado será la creacion del servicio así:

CREATE src/twits/twits.service.ts (89 bytes)

CREATE src/twits/twits.service.spec.ts (453 bytes)

UPDATE src/app.module.ts (394 bytes)

y lo colocará dentro de la carpeta twits del controlador twits

el servicio no es más que una clase que contiene el decorador ¿injevctable ejemplo 

import { Injectable } from '@nestjs/common';

@Injectable()
export class TwitsService {}


el twits.service.sts será el proveedor principal apara el twits controller, será quien le inyectrará toda la logica de negociio.

así crearé iun costrictr en la twit.controller e injecto el servciio+

import {
  Body,
  Controller,
  Delete,
  Get,
  HttpCode,
  HttpStatus,
  Param,
  Patch,
  Post,
  Query,
} from '@nestjs/common';
import { TwitsService } from './twits.service';

// controlador  sierve para enrrutar
@Controller('twits')
export class TwitsController {
  constructor(private readonly twitService: TwitsService) {}


así estoy uniendo en controlador co su respectivo servicio

ahora se va a crear una entidad

 dentro de l a carpeta twits

twits.entity.ts

dentro de  este archivo entidad creo una clase exportatable llamada twit que me servirá de tipo 

export class Twits {
  id: string;
  menssage: string;
}

ahora en el servicio puedo usar esta entidad

import { Injectable } from '@nestjs/common';
import { Twits } from './twits.entity';

@Injectable()
export class TwitsService {
  private twits: Twits[];
}


creo ahora la logica de negocio en le servicio

import { Injectable } from '@nestjs/common';
import { Twits } from './twits.entity';

@Injectable()
export class TwitsService {
  // creo un ejmlo para trabajar
  private twits: Twits[] = [
    {
      id: '1',
      menssage: 'hola aqui estoy',
    },
  ];
  // creo un funcion que traiga los miembros de la lista
  getTwits(): Twits[] {
    return this.twits;
  }
  getTwit(id: string): Twits {
    return this.twits.find((item) => item.id === id);
  }
  createTwit(menssage: string): void {
    this.twits.push({
      id: Math.floor(Math.random() * 2000 + 1).toString(),
      menssage: menssage,
    });
  }
  updateTwit(id: string, menssage: string): Twits {
    const twit: Twits = this.getTwit(id);
    twit.menssage = menssage;
    return twit;
  }
  removeTwit(id: string): void {
    const index = this.twits.findIndex((twit) => twit.id === id);
    if (index >= 0) {
      this.twits.splice(index, 1);
    }
  }
}

ahora puedo ir al controlador para poder usar estos metodos creado

import {
  Body,
  Controller,
  Delete,
  Get,
  //HttpCode,
  //HttpStatus,
  Param,
  Patch,
  Post,
  Query,
} from '@nestjs/common';
import { TwitsService } from './twits.service';
import { Twits } from './twits.entity';

// controlador  sierve para enrrutar
@Controller('twits')
export class TwitsController {
  constructor(private readonly twitService: TwitsService) {}
  //@Get es un decorador que sirve para ordenar los llamados get
  //el decorador query sirve para pasar parametros filtrados
  @Get()
  getTwits(): Twits[] {
    return this.twitService.getTwits();
  }
  @Get()
  getTwitsFilter(@Query() filterQuery): Twits[] {
    // para establecerel filtro de busqueda
    const { searchTerm, orderBy } = filterQuery;
    return this.twitService.getTwits();
  }
  //@param puede recibir parametros por la url
  @Get(':id')
  // los para,etros siempre vinen como string aunque sean numeros
  getTwit(@Param('id') id: string): Twits {
    return this.twitService.getTwit(id);
  }
  @Post()
  //para colocar el estado de la respuesta htth
  //@HttpCode(HttpStatus.NO_CONTENT)
  //@Body recibe la información del cuerpo de la peticipn http post
  createTwit(@Body('menssage') menssage: string): void {
    return this.twitService.createTwit(menssage);
  }
  @Patch(':id')
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  updateTwit(@Param('id') id: string, @Body('menssage') twit: string): Twits {
    return this.twitService.updateTwit(id, twit);
  }
  @Delete(':id')
  remuveTwit(@Param('id') id: string): void {
    return this.twitService.removeTwit(id);
  }
}

0 comentarios:

Publicar un comentario