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
6,622
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:
./src/ts-runtime-validation/validation.schema.json
- containing the jsonschema types./src/SchemaDefinition.ts
- containing the typescript../src/isValidSchema.ts
- containing a type guard type inferring helper method (intended for consumption in your code base - examples below)./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