npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@davidk01/tiny-validator

v2.0.2

Published

Small validation library using type guards along with conditional and mapped types

Downloads

5

Readme

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":["",""]}]}