Validating Typescript Data Transfer Objects with Firefly Semantics Validator | Task

Ole Ersoy
Nov - 12  -  2 min

Scenario

We are receiving data transfer object instances with a PurchaseOrderDTO type and we need to validate them using Firefly Semantics Validator.

Approach

The PurchaseOrderDTO has been annotated with Firefly Semantics Validator validation annotations as follows:

import {
  IsNumberString,
  IsISODateString,
  IsDefined,
  IsString,
} from '@fireflysemantics/validator';

export class PurchaseOrderDTO {
  @IsString()
  @IsDefined()
  id: string;
  @IsString()
  @IsDefined()
  sku: string;

  @IsISODateString()
  @IsString()
  @IsDefined()
  purchaseDate: string;

  @IsISODateString()
  @IsString()
  @IsDefined()
  receiptDate: string;

  @IsNumberString()
  @IsString()
  @IsDefined()
  quantity: string;
  constructor(o: any) {
    Object.assign(this, o);
  }
}

We will create an instance an validate it:

const poDTOValid: PurchaseOrderDTO = new PurchaseOrderDTO(
{
    sku: 'skuABC',
    id: '123',
    purchaseDate: '2021-11-22',
    receiptDate: '2021-11-28',
    quantity: '2',
});
const oeValid: ObjectErrors = validate(poDTOValid);
assert.equal(oeValid.errors.length, 0, 'There should be 0 errors');

In this case there are no errors, as all the properties are valid.

Lets create another instance with no valid properties:

const poDTOInvalid1: PurchaseOrderDTO = new PurchaseOrderDTO({});
const oeInvalid: ObjectErrors = validate(poDTOInvalid1);
assert.equal(oeInvalid.errors.length, 5, 'There should be 5 errors');

In this case the @IsDefined annotation is triggered 5 times, creating 5 ValidationError error instances.

Demo