Firefly Semantics Validator API Basics | Task

Ole Ersoy
Nov - 13  -  2 min

Scenario

We have a PurchaseOrder class that has been annotated with Firefly Semantics Validator decorators.

import {
  IfValid,
  IsAfterInstant,
  IsDate,
  IsDefined,
  IsString,
  IsInt,
} from '@fireflysemantics/validator';

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

  @IsDate()
  @IsDefined()
  purchaseDate: Date;

  @IsAfterInstant('purchaseDate')
  @IsDate()
  @IsDefined()
  @IfValid('purchaseDate')
  receiptDate: Date;

  @IsInt()
  @IsDefined()
  quantity: number;
  constructor(o: any) {
    //===================================
    // Initialize the sku and id properties
    // with Object.assign
    //===================================
    Object.assign(this, o);
  }
}

Now we want to learn how to use the Firefly Semantics ValidatorAPI to validate:

  • A single property
  • A single PurchaseOrder instance.
  • Multiple PurchaseOder instances.

Approach

Create a new PurchaseOrder instance:

const po: PurchaseOrder = new PurchaseOrder(
{
sku: 'skuABC',
id: '123',
purchaseDate: new Date('2021-11-22'),
receiptDate: new Date('2021-11-28'),
quantity: 2,
});

Single Purchase Order Property Validation

let valid: boolean = validateProperty(po, 'sku');
assert.equal(valid, true, 'valid should be true');
po.sku = null;
valid = validateProperty(po, 'sku');
assert.equal(valid, false, 'valid should be false');

Single Purchase Order Instance Validation

To validate a single instance we use validate :

const OE: ObjectErrors = validate(po);
let errors: ValidationError[] = OE.errors;
assert.equal(OE.valid, false, 'valid should be false');
assert.equal(
errors.length,
1,
'There should be one error for the SKU property'
);
//console.log(errors[0].message);
assert.equal(
errors[0].message.includes('sku'),
true,
'The invalid property is the sku propertyy'
);

Validation of Multiple Purchase Order Instances

To validate multiple instances we place them in an array and use validateN([po1, po2, po3]):

const OES: ObjectErrors[] = validateN([po]);
//console.log(OES);
assert.equal(OES.length, 1, 'There should be one error');
assert.equal(OES[0].valid, false, 'Valid should be false');
errors = OES[0].errors;
assert.equal(
errors.length,
1,
'There should be one error for the SKU property'
);
//console.log(errors[0].message);
assert.equal(
errors[0].message.includes('sku'),
true,
'The invalid property is the sku property'
);

Demo