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

ts-runtime-validation

v1.6.10

Published

A set of tools to generate json-schema validations from typescript interface(s) and methods to validate unknown data at runtime against them

Downloads

7,605

Readme

ts-runtime-validation

Why?

Get bulletproof type validation based off typescript interfaces without any extra work. This package will ingest your existing types and generate the code for you.

How?

This is a code generator that is designed to run as a yarn / npm script. By default scans your source directory for files ending in the provided glob pattern. It will generate types based off exported type aliases and typescript interfaces. By default: *.jsonschema.{ts,tsx}. The output will create three files:

  1. ./src/ts-runtime-validation/validation.schema.json - containing the jsonschema types
  2. ./src/SchemaDefinition.ts - containing the typescript.
  3. ./src/isValidSchema.ts - containing a type guard type inferring helper method (intended for consumption in your code base - examples below)
  4. ./src/ValidationType.ts - containing an exported namespace containing every single exported validation type

Limitations

The schema generator does not allow multiple interfaces / types to share the same name.

Footnote

The helper file assumes you have ajv-validator peer dependency installed. Since this is only a code generation tool this package can be installed as a dev dependency.

Installation

# yarn
yarn add --dev ts-runtime-validation
# npm
npm install --dev ts-runtime-validation

CLI usage

Ensure your project files containing the schemas you want to validate end with the prefix .jsonschema.ts

Usage: ts-runtime-validation [options]

Options:
  --glob                         Glob file path of typescript files to generate ts-interface -> json-schema validations - default: *.jsonschema.{ts,tsx}
  --rootPath <rootFolder>        RootPath of source (default: "./src")
  --output <outputFolder>        Code generation output directory (relative to root path) (default: "./.ts-runtime-validation")
  --tsconfigPath <tsconfigPath>  Path to customt tsconfig (relative to root path) (default: "")
  --generate-helpers             Only generate JSON schema without typescript helper files (default: true)
  --additionalProperties         Allow additional properties to pass validation (default: false)
  -h, --help                     display help for command
Done in 0.44s.

npm script usage

The intended use for ts-runtime-validation is as a npm script. Here it can also be tweaked to watch (eg. using nodemon)

{
    "scripts": {
        "generate-types": "ts-runtime-validation"
    },
    "devDependencies": {
        "ts-runtime-validation": "^1.4.1"
    }
}

Example snippets

Type guard

import { isValidSchema } from "./.ts-runtime-validation/isValidSchema"; // this is autogenerated by the CLI as a helper file

if (isValidSchema(data, "#/definitions/ITypeA")) {
    // variable: data in this block will have typings for ITypeA
} else {
    // type is invalid and not known here
    throw new Error("Failed to validate payload");
}

Type assertion

import * as schema from "../runtime-validation/validation.schema.json";
import Ajv from "ajv";
import { ISchema, schemas } from "../runtime-validation/SchemaDefinition";

const validator = new Ajv({ allErrors: true });
validator.compile(schema);

export const assertValidSchema = <T extends keyof typeof schemas>(data: unknown, schemaKeyRef: T): data is ISchema[T] => {
    validator.validate(schemaKeyRef as string, data);
    if (validator.errors || Boolean(validator.errors)) {
        const error = { schemaKeyRef, errors: validator.errorsText(), data };
        if (process.env.ENVIRONMENT === "dev") {
            console.log(error);
        }
        throw new Error(JSON.stringify(error));
    }
    return true;
};

Contributing

Submit a PR

License

MIT