Categorias
iiiiii
Pipes Personalizados
Descripcion
Crear un pipe automatico. usand CLI nest
Nota1
Que es un pipe: es una simple clase.
1.Creamos un modulo para manejarlos
nest g mo common
2. creamos un pipe dentro del modulo
nest g pi common/pipes/parseMongoId
Modulo
import { ArgumentMetadata, Injectable, PipeTransform, BadRequestException } from '@nestjs/common';
import { isValidObjectId } from 'mongoose';
@Injectable()
export class ParseMongoIdPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
if(!isValidObjectId(value)){
throw new BadRequestException(`el ${value} is not mongoId valid`);
}
return value;
}
}
Servicio
import { Injectable, Body, Post, Controller, BadRequestException, InternalServerErrorException, NotFoundException } from '@nestjs/common';
import { CreatePokemonDto } from './dto/create-pokemon.dto';
import { UpdatePokemonDto } from './dto/update-pokemon.dto';
import { InjectModel } from '@nestjs/mongoose/dist/common';
import { isValidObjectId, Model } from 'mongoose';
import { Pokemon } from './entities/pokemon.entity';
import { json } from 'stream/consumers';
import { allowedNodeEnvironmentFlags } from 'process';
@Injectable()
export class PokemonService {
constructor(
@InjectModel(Pokemon.name)
private readonly PokemonModel:Model<Pokemon>){
}
async remove(id: string) {
//const pokemon = await this.findOne(id);
//await pokemon.deleteOne();
//const rest = await this.PokemonModel.findByIdAndDelete(id);
const rest = await this.PokemonModel.deleteOne({_id:id});
if(rest.deletedCount==0){
throw new BadRequestException('No existe nada para eliminar');
}
}
}
Controlador
import { Controller, Get, Post, Body, Patch, Param, Delete, HttpCode } from '@nestjs/common';
import { PokemonService } from './pokemon.service';
import { CreatePokemonDto } from './dto/create-pokemon.dto';
import { UpdatePokemonDto } from './dto/update-pokemon.dto';
import { ParseMongoIdPipe } from '../common/pipes/parse-mongo-id/parse-mongo-id.pipe';
@Controller('pokemon')
export class PokemonController {
constructor(private readonly pokemonService: PokemonService) {}
@Delete(':id')
remove(@Param('id',ParseMongoIdPipe) id: string) {
return this.pokemonService.remove(id);
}
}