Validating Typescript Business Entities with Firefly Semantics Validator

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

Founder of Firefly Semantics Corporation

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Building TS Packages: Anatomy Of A React StoryBook TSDX Project

Creating a Angular Material Kitchen Sink Base Module

Understanding CSS Box Model

Starting my own Game Studio-on the ease and the power of SVG

How to Launch Your MVP Server in an Hour

React as a UI Editor

Fun With Faces

readable — new PHP linter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation

More from Medium

[React] Unit Testing APIs with Mock Service Worker (MSW)

JavaScript Control Flow & Error Handling

Introduction to Auth0 Actions

MongoDB: How To Find Duplicate Documents In Collection