1.6.10 • Published 10 months ago

ts-runtime-validation v1.6.10

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

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

1.6.4

10 months ago

1.6.3

10 months ago

1.6.2

10 months ago

1.6.1

10 months ago

1.6.0

10 months ago

1.5.0

10 months ago

1.6.9

10 months ago

1.6.8

10 months ago

1.6.10

10 months ago

1.6.7

10 months ago

1.6.6

10 months ago

1.6.5

10 months ago

1.4.1

1 year ago

1.4.0

1 year ago

1.2.8

2 years ago

1.2.7

2 years ago

1.3.0

2 years ago

1.2.6

2 years ago

1.2.5

2 years ago

1.2.3

2 years ago

1.2.2

2 years ago

1.2.1

2 years ago

1.2.0

2 years ago

1.1.5

2 years ago

1.1.4

2 years ago

1.1.3

2 years ago

1.1.2

2 years ago

1.1.1

2 years ago

1.1.0

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago