Battle-tested runtime type checker for Typescript using JSON Schema type guards.
All you have to do is installing the package:
$ npm i runtypor
Here is a simple example of request input validation with Express:
import express from 'express';
import { createRuntype } from '../src/index';
type Car = {
brand: string;
model: string;
manufacturedAt: string;
color: string;
price: number;
}
// JSON Schema from ajv
// @see https://github.com/epoberezkin/ajv#getting-started
const validationSchema = {
type: 'object',
properties: {
brand: { type: 'string' },
model: { type: 'string' },
manufacturedAt: { type: 'string', format: 'date-time' },
color: { type: 'string', default: 'green' },
price: { type: 'number' },
},
required: ['brand', 'model'],
};
const carRuntype = createRuntype<Car>(validationSchema);
app.post('/car-purchase', (req: express.Request, res: express.Response): void => {
const car = req.body;
if (!carRuntype.match(car)) {
res.status(400).send(carRuntype.badType.message);
// throw carRuntype.badType; // In some cases, you may throw an error.
} else {
const newPrice = computeReduction(Number.parseInt(car.price, 10)); // OK
// ...
}
});
By default, runtype create a naive clone (JSON.parse(JSON.stringify(value))
) in order to prevent mutation of matched value.
In that example, it would be useful to retrieve the validated and mutated clone with coerced types and default values:
// ...
app.post('/car-purchase', (req: express.Request, res: express.Response): void => {
const car = req.body;
if (!carRuntype.match(car)) {
res.status(400).send(carRuntype.badType.message);
} else {
const validatedCar = carRuntype.validatedValue;
const newPrice = computeReduction(validatedCar.price);
carBuilder.setColor(validatedCar.color); // Default to green.
}
});
Note that you should only use the validated value when your data has a simple JSON structure, as it won't replicate prototypal chain or functions for instance.
Do you prefer object notation over functional one ? Use the class instantiation:
import { createRuntype, Runtype } from '../src/index';
// ...
createRuntype<Car>(validationSchema);
// is equivalent to
new Runtype<Car>(validationSchema);
Many npm
scripts are available to help testing:
$ npm run {script}
check
: lint and check unit and integration testslint
: lintlint-fix
: try to fix lint automaticallytest
: execute teststest-coverage
: execure tests with coverage informationstest-watch
: work in TDD !
Use npm run check
to check that everything is ok.
If you want to contribute, just fork this repository and make a pull request !
Your development must respect these rules:
- fast
- easy
- light
You must keep test coverage at 100%.