@tapraise/sandboxed-input
Sandbox wrapper around input that allows you to postpone the validation until you actually need it, removing the need to define a complete validation schema for it, up-front.
Features:
- full Typescript support
- additional functionality to sanitize and transform data before usage.
- easily add your own validators, sanitizers and transformers, by implementing Typescript interfaces
It works around expectations you define, like:
// Expect input to have a required string property
const gender: string = input.getString('gender').value;
// Expect input to have an optional, numeric amount property
const amount: number | null | undefined =
input.getOptionalNumber('amount').value;
On top of that you can do additional, type based validation, input sanitizing and input transforming, all with full Typescript support, like:
/**
* given input:
*
* {
* "name": {
* "first": "Peter",
* "last": null
* },
* "age": "12"
* }
*/
import { SandboxedObject, MinLength, MaxLength, Trim, StringToInt } from '@tapraise/sandboxed-input';
const input = SandboxedObject.createFromRawInput(JSON.parse(jsonString));
const firstName: string = input
.getObject('name')
.getString('first')
.validate(new MinLength(1), new MaxLength(255))
.sanitize(new Trim()).value;
const lastName: string | null = input
.getObject('name')
.getNullableString('last') // allows the property to have a null value, too
.validate(new MinLength(1)).value; // validatir is only applied when the value is actually there
const noExistant: boolean | null | undefined =
input.getOptionalBoolean('doesntExist').value;
const age: number = input
.getString('age')
.sanitize(new Trim())
.validate(new Numeric())
.transform(new StringToInt()) // transform Typescript types from string to number
.validate(new Min(18), new Max(80)).value;
Useful for:
- external API input handling
- start working quickly with data, without having to know it completely up front
- handling of complex or less structured data
How to install
npm install --save @tapraise/sandboxed-input
(or whatever package manager you use)
Contribution
Development
To contribute, prepare your dev environment by creating a fork of the repository.
Once cloned locally, be sure to have PNPM installed, and install the dev dependencies locally by running
pnpm install
To start the typescript compiler in watch mode:
pnpm build:watch
To run the tests in watch mode:
pnpm test:watch
Publishing
To publish a new version, use:
pnpm version <patch|minor|major>
to create a new tag and version reference in package.json
, and then publish with:
pnpm publish
For other custom scripts, see:
pnpm run