Skip to content

Instantly share code, notes, and snippets.

@redeemefy
Last active January 27, 2022 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redeemefy/c0c8606fb7efbbe62116bfda2ee83096 to your computer and use it in GitHub Desktop.
Save redeemefy/c0c8606fb7efbbe62116bfda2ee83096 to your computer and use it in GitHub Desktop.
Validate MongodbId automatically with ValidationPipe and a class dto
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({ // class-validator class-transformer for DTOs
transform: true, // converts payload to DTO classes in the controller
whitelist: true, // strip out props are not in DTOs
forbidNonWhitelisted: true, // return error if props not in DTOs are in payload
}))
await app.listen(3000);
}
bootstrap();
import { IsMongoId } from "class-validator";
import { ObjectId } from "mongoose";
export class UpdateResourceParamDto {
@IsMongoId()
readonly id: string;
}
import { Controller, Get } from '@nestjs/common';
import { UpdateResourceParamDto } from './dto/update-resource-param.dto';
import { ResourceService } from './resource.service';
@Controller('questions')
export class QuestionsController {
constructor(private readonly resourceService: ResourceService) {}
@Get(':id')
findOne(@Param() { id }: UpdateResourceParamDto) {
return this.resourceService.findOne(id)
}
}
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Resource } from './schemas/resource.schema';
@Injectable()
export class ResourceService {
constructor(@InjectModel(Resourse.name) private readonly resourceModel: Model<Resource>){}
...
async findOne(id: string) { // There is no dto here
const resource = await this.resourceModel.findById(id)
if(!resource) {
throw new NotFoundException(`Resource id: ${id} not found.`)
}
return resource
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment