Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

nestjs custom error class validator

import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'
import { validate } from 'class-validator'
import { plainToClass } from 'class-transformer'

import { apiResponse } from '@helpers/helper.apiResponse'

@Injectable()
export class ValidationPipe implements PipeTransform<any> {
	async transform(value: any, { metatype }: ArgumentMetadata) {
		if (!metatype || !this.toValidate(metatype)) {
			return value
		}

		const object = plainToClass(metatype, value)
		const errors = await validate(object)

		if (errors.length > 0) {
			const errorsResponse: any = errors.map((val: any) => {
				return apiResponse(400, Object.values(val.constraints)[0] as string)
			})
			throw new BadRequestException({ errors: errorsResponse })
		}
		return value
	}

	private toValidate(metatype: Function): boolean {
		const types: Function[] = [String, Boolean, Number, Array, Object]
		return !types.includes(metatype)
	}
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: http request node.js 
Javascript :: toggle password hide show 
Javascript :: Javascript Map properties and methods 
Javascript :: pylint vscode disable max line length 
Javascript :: how to run socket.io server 
Javascript :: reduce 
Javascript :: how to display date in javascript 
Javascript :: json to array javascript 
Javascript :: react native elements 
Javascript :: javascript call php function with parameters 
Javascript :: javascript remove required attribute 
Javascript :: angular pass async pipe value to funciton 
Javascript :: update query in mongoose 
Javascript :: on button click show collapse div jquery 
Javascript :: use react awesome slider in react js 
Javascript :: js check if image url exists 
Javascript :: react particles 
Javascript :: angular subscribe on value change 
Javascript :: singleton function javascript 
Javascript :: javascript console 
Javascript :: check data type in js 
Javascript :: material ui textfield with chips 
Javascript :: double logical not javascript 
Javascript :: javascript change _ to space 
Javascript :: javaScript setFullYear() Method 
Javascript :: function to count words in string 
Javascript :: random number generatoe js 
Javascript :: how to create a class javascript 
Javascript :: how to get the uppert triangular matrix out of a matrix matlab 
Javascript :: node js split 
ADD CONTENT
Topic
Content
Source link
Name
5+4 =