Validating Typescript Business Entities with Firefly Semantics Validator

Ole Ersoy
2 min readNov 13, 2021
Image by Eelffica from Pixabay

Scenario

We have PurchaseOrderDTO decorated with Firefly Semantics Validator decorators.

The instances are coming in over the wire as described here.

We wish to construct PurchaseOrder instances using the PurchaseOrderDTO instances and then validate the following:

  • The quantity is an integer
  • Both the purchaseDate and the receiptDate are Date instances.
  • The purchaseDate comes before the receiptDate
  • The receiptDate will only be validated if the purchaseDate is valid. This functionality is provided by the @IfValid decorator and prevents validation noise.

Approach

After the PurchaseOrderDTO has been validated we drop it in to a PurchaseOrder constructor. The PurchaseOrder class is defined below:

We use Object.assign to set the sku and id properties as these are string typed and can be mapped directly.

We create typed instances of the variables:

  • quantity
  • receiptDate
  • purchaseDate

After PurchaseOrder instance construction we can validate the instance like this:

const poDTO1: PurchaseOrderDTO = new PurchaseOrderDTO({});const poInvalid: PurchaseOrder = new PurchaseOrder(poDTO1);const poInValid: ObjectErrors = validate(poInvalid);const errors: ValidationError[] = poInValid.errors;assert.equal(poInValid.errors.length, 5, 'There should be 5 errors');

In this case we can see that 5 errors are generated. One for each property.

Demo

Related Concepts

--

--