UNPKG

denwa-nest-shared

Version:

Shared NestJS module for DTO validation, RBAC, TypeORM query building, and OpenAPI client

57 lines • 2.41 kB
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { HttpStatus, Injectable } from '@nestjs/common'; import { plainToClass } from 'class-transformer'; import { validate } from 'class-validator'; import { ValidationException } from './validation.exception'; let ValidationPipe = class ValidationPipe { async transform(value, metadata) { if (!metadata.metatype || !this.toValidate(metadata.metatype) || (value && typeof value === 'object' && 'fieldNodes' in value)) { return value; } const obj = plainToClass(metadata.metatype, value ?? {}); if (!obj || typeof obj !== 'object') return value; const errors = await validate(obj); if (errors.length) { const messages = this.formatErrors(errors); const response = { statusCode: HttpStatus.BAD_REQUEST, error: 'Bad request', messages, }; throw new ValidationException(response); } return value; } toValidate(metatype) { const types = [String, Boolean, Number, Array, Object]; return !types.includes(metatype); } formatErrors(errors) { const messages = []; for (const err of errors) { if (err.constraints) { messages.push(`${err.property} - ${Object.values(err.constraints).join(', ')}`); } else if (err.children && err.children.length > 0) { messages.push(...this.formatErrors(err.children).map((subMsg) => `${err.property}.${subMsg}`)); } else { messages.push(err.property); } } return messages; } }; ValidationPipe = __decorate([ Injectable() ], ValidationPipe); export { ValidationPipe }; //# sourceMappingURL=validation.pipe.js.map