gg-dto-validator
v1.0.11
Published
custom rxjs operator responsible for object creation and validation
Downloads
35
Maintainers
Readme
DTO Validator
DTO VALIDATOR is custom rxjs operator responsible for:
- object creation based on class-transformer library
- DTO validation
Pipe uses class-transformer npm package to create class instanced based on provided class type. Created instance is then verified with class-validator package. On success pipe returns created class instance. On invalid DTO it throws error (instance of DtoError class) with list of errors.
USE EXAMPLE
- Install npm package
npm install gg-dto-validator
- Create Class DTO with class-validator decorators
import { IsNotEmpty, IsNumber, IsInt, IsString } from 'class-validator';
export class AnimalDTO {
@IsNotEmpty()
@IsInt()
id: number;
@IsNotEmpty()
@IsString()
name: string;
@IsNotEmpty()
@IsNumber()
years: number;
method(): void {
// do sth
}
}
- Use ggpDTO rxjs operator in service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ggDTO } from 'gg-dto-validator';
@Injectable()
export class AppService {
constructor(private http: HttpClient) {}
getAnimals(): Observable<AnimalDTO> {
return this.http
.get<unknown>('http://api-url/animals')
.pipe(ggpDTO(AnimalDTO));
}
}
- Creating DTO for ggpDTO rxjs operator with nested array of objects
import { Type } from 'class-transformer';
import { IsArray, IsNotEmpty, ValidateNested } from 'class-validator';
export class AnimalListDTO {
@IsNotEmpty()
@IsArray()
@ValidateNested({ each: true })
@Type(() => AnimalDTO)
items: AnimalDTO[];
}