gg-dto-validator

custom rxjs operator responsible for object creation and validation

Usage no npm install needed!

<script type="module">
  import ggDtoValidator from 'https://cdn.skypack.dev/gg-dto-validator';
</script>

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

  1. Install npm package
npm install gg-dto-validator
  1. 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
  }
}
  1. 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));
  }
}
  1. 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[];
}