@davidk01/tiny-validator
TypeScript icon, indicating that this package has built-in type declarations

2.0.2 • Public • Published

What is it?

Tiny validation library that leverages type guards, conditional types, and mapped types to provide basic compile time help for writing type guards for POJO (plain old javascript object) payload types.

Example

Take a look at test/test.ts for a use case. It is inlined below with an explanation of what is going on.

First we have to define the payload type for the POJO (plain old javascript object). We are using nullable fields because we want the compiler to complain if we accidentaly use the POJO type directly in the code. The type guard returns Strict<T> if the validation is successful and Strict<T> is a mapped type which converts all nullable fields to non-null fields. It's defined in src/index.ts if you want to take a look. Anyway, carrying on with the example

import * as validation from '../src/index';

type Payload = {
  f1?: string,
  f2?: string[],
  f3?: {
    f1?: number,
    f2?: string[]
  }[]
};

Next we must define the validation type

type PayloadValidation = validation.CombinedValidated<Payload>

With the validation type defined we can create the description of the validation

const payloadValidation: PayloadValidation = {
  f1: { type: 'string', valid: _ => true },
  f2: [{ type: 'string', valid: _ => true }],
  f3: [{
    f1: { type: 'number', valid: _ => true },
    f2: [{ type: 'string', valid: _ => true }]
  }]
};

Notice how each key in the payload is mapped to an object that specifies the type and a validation function that will take the input at the specified key and then return true or false to indicate whether the field is valid. In a production environment valid wouldn't vacuously return true but would actually be a function that incorporates some domain knowledge.

Now let's define two payloads. One will be valid and the other will be invalid

const validPayload: Payload = {
  f1: '',
  f2: [''],
  f3: [
    {
      f1: 0,
      f2: ['']
    }
  ]
};
const invalidPayload: Payload = {
  f1: '',
  f2: [''],
  f3: [
    {
      f1: 0,
      f2: ['', '']
    }
  ]
};

The reason the second payload is invalid is a little subtle. In our validation prototype we defined f3[0].f2 to be an array with a single element but in the payload we are supplying two elements. Since the length doesn't match the payload is considered invalid.

Let's actually run and verify that the valid and invalid payloads are marked as such

// Valid payload
if (validation.validator<Payload>(validPayload, payloadValidation)) {
  console.log('Received valid payload', JSON.stringify(validPayload));
} else {
  console.log('Invalid payload', JSON.stringify(validPayload));
}

// Invalid payload b/c invalidPayload.f3.f2 has an extra key
if (validation.validator<Payload>(invalidPayload, payloadValidation)) {
  console.log('Received valid payload', JSON.stringify(invalidPayload));
} else {
  console.log('Received invalid payload', JSON.stringify(invalidPayload));
}

First check will print the true arm of the if statement and the second will print the false arm because of the length mismatch in one of the arrays.

$ tsc test/test.ts && node test/test/js
Received valid payload {"f1":"","f2":[""],"f3":[{"f1":0,"f2":[""]}]}
Received invalid payload {"f1":"","f2":[""],"f3":[{"f1":0,"f2":["",""]}]}

Readme

Keywords

Package Sidebar

Install

npm i @davidk01/tiny-validator

Weekly Downloads

0

Version

2.0.2

License

MIT

Unpacked Size

7.54 kB

Total Files

5

Last publish

Collaborators

  • davidk01